> ## Documentation Index
> Fetch the complete documentation index at: https://seilabs-docs-evm-cookbook.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# JSON Precompile Usage

> Learn how to interact with Sei's JSON precompile through ethers.js, enabling efficient parsing, manipulation, and querying of JSON data within EVM smart contracts to overcome Solidity's native limitations for handling complex data structures.

**Address:** `0x0000000000000000000000000000000000001003`

The Sei JSON precompile lets EVM applications parse and query JSON data efficiently, directly within smart contracts. Solidity does not support this kind of complex data handling natively. The precompile makes it easier to work with structured data from external sources or APIs.

<Info>**What is a precompile?** A precompile is a special smart contract that the Sei protocol itself deploys at a fixed address. It exposes custom native chain logic to EVM-based applications. To the EVM, it behaves like a regular contract, but it executes privileged, low-level logic efficiently.</Info>

## How does the JSON precompile work?

The JSON precompile at address `0x0000000000000000000000000000000000001003` exposes `extractAsBytes()`, `extractAsBytesList()`, `extractAsBytesFromArray()`, and `extractAsUint256()`.

* EVM contracts and dApps can call the JSON parsing functions directly, like any other smart contract method.
* JSON parsing runs at the native level, which makes it efficient.
* You do not need complex workarounds or external libraries to handle JSON.

## Use cases

* **Oracle integration:** Parse complex oracle responses that contain multiple data points.
* **DeFi applications:** Process structured price feeds and market data.
* **Gaming:** Handle complex game state and player data stored in JSON format.
* **Cross-chain communication:** Parse messages and data from other chains.
* **NFT metadata:** Extract and manipulate NFT metadata stored in JSON format.

## Functions

The JSON precompile exposes these functions:

### Query functions

```solidity theme={null}
/// Extracts data as bytes from the input using the specified key.
/// @param input The input data.
/// @param key The key to extract.
/// @return The extracted data as bytes.
function extractAsBytes(
    bytes memory input,
    string memory key
) external view returns (bytes memory response);

/// Extracts data as a list of bytes from the input using the specified key.
/// @param input The input data.
/// @param key The key to extract.
/// @return The extracted data as bytes collection.
function extractAsBytesList(
    bytes memory input,
    string memory key
) external view returns (bytes[] memory response);

/// Extracts one element from a JSON array by index.
/// @param input The input data.
/// @param arrayIndex The zero-based array index.
/// @return The extracted data as bytes.
function extractAsBytesFromArray(
    bytes memory input,
    uint16 arrayIndex
) external view returns (bytes memory response);

/// Extracts data as a uint256 from the input using the specified key.
/// @param input The input data.
/// @param key The key to extract.
/// @return The extracted uint256.
function extractAsUint256(
    bytes memory input,
    string memory key
) external view returns (uint256 response);
```

## Using the precompile

### Setup

#### Prerequisites

Before you start, make sure that you have:

* Node.js (v18 or higher)
* The npm or yarn package manager
* MetaMask or another compatible EVM wallet, configured for Sei Mainnet
* SEI tokens for gas

#### Install dependencies

Install the required packages to interact with Sei precompiles:

```bash theme={null}
# Install ethers.js for smart contract interactions
npm install ethers

# Install @sei-js/precompiles for precompile addresses and ABIs
npm install @sei-js/precompiles@^3

# Install dotenv for managing private keys (recommended for security)
npm install dotenv
```

#### Import precompile components

```typescript theme={null}
// Import JSON precompile address and ABI
// View the entire ABI here: https://github.com/sei-protocol/sei-chain/blob/v6.6.1/precompiles/json/legacy/v66/abi.json
import { JSON_PRECOMPILE_ABI, JSON_PRECOMPILE_ADDRESS } from '@sei-js/precompiles';
import { ethers } from 'ethers';
```

<Info>**Precompile address:** The JSON precompile is deployed at `0x0000000000000000000000000000000000001003`.</Info>

### Contract initialization

Set up your provider, signer, and contract instance:

```typescript theme={null}
// Using MetaMask as the signer and provider (browser environment)
const provider = new ethers.BrowserProvider(window.ethereum);
await provider.send('eth_requestAccounts', []);
const signer = await provider.getSigner();

// Or for Node.js environment
const provider = new ethers.JsonRpcProvider('https://evm-rpc.sei-apis.com');
const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

// Create a contract instance for the JSON precompile
const jsonPrecompile = new ethers.Contract(JSON_PRECOMPILE_ADDRESS, JSON_PRECOMPILE_ABI, signer);
```

## Data type handling

The JSON precompile has specific limitations for different data types:

### Supported data types

| Function | Supports | Limitations |
| - | - | - |
| extractAsBytes | Strings, objects, arrays | Returns raw bytes that need conversion |
| extractAsUint256 | Integers only | No decimals, booleans, or negative numbers |
| extractAsBytesList | Arrays of strings/objects | Returns each element as bytes |

<Warning>**Value length limit:** Make sure that the numeric values you pass stay within 100 characters. `extractAsUint256` rejects value strings longer than 100 characters. If the numeric string extracted for the given key is longer than this, the call fails with `value string too long`.</Warning>

### Data type conversion strategies

```typescript theme={null}
// For decimal numbers - store as integers with known precision
const priceData = { price: 250 }; // Represents 2.50 with 2 decimal places
const price = await jsonPrecompile.extractAsUint256(inputData, 'price');
const actualPrice = parseFloat(price.toString()) / 100; // Convert back to 2.50

// For boolean values - use 0/1 integers
const statusData = { isActive: 1 }; // 1 = true, 0 = false
const isActiveInt = await jsonPrecompile.extractAsUint256(inputData, 'isActive');
const isActive = isActiveInt === 1n;

// For complex objects - extract as bytes and parse
const userData = { user: { name: 'Alice', balance: 1000 } };
const userBytes = await jsonPrecompile.extractAsBytes(inputData, 'user');
const userString = ethers.toUtf8String(userBytes);
const userObject = JSON.parse(userString);
```

## Error handling utilities

Add error handling to all extraction functions:

```typescript theme={null}
// Safe extraction for bytes data
async function safeExtractBytes(jsonPrecompile: ethers.Contract, data: any, key: string, defaultValue: string = ''): Promise<string> {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsBytes(inputData, key);
    return ethers.toUtf8String(result);
  } catch (error: any) {
    console.log(`Key "${key}" not found or invalid, using default value`);
    return defaultValue;
  }
}

// Safe extraction for uint256 data
async function safeExtractUint256(jsonPrecompile: ethers.Contract, data: any, key: string, defaultValue: bigint = 0n): Promise<bigint> {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsUint256(inputData, key);
    return result;
  } catch (error: any) {
    console.log(`Key "${key}" not found or not a valid integer, using default value`);
    return defaultValue;
  }
}

// Safe extraction for array data
async function safeExtractBytesList(jsonPrecompile: ethers.Contract, data: any, key: string, defaultValue: string[] = []): Promise<string[]> {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsBytesList(inputData, key);
    return result.map((bytes: any) => ethers.toUtf8String(bytes));
  } catch (error: any) {
    console.log(`Key "${key}" not found or not a valid array, using default value`);
    return defaultValue;
  }
}
```

## Step-by-step guide: Using the JSON precompile

### Extract string data

```typescript theme={null}
// JSON data with string values
const data = { name: 'Sei Token', symbol: 'SEI' };
const inputData = ethers.toUtf8Bytes(JSON.stringify(data));

// Extract string using safe method
const name = await safeExtractBytes(jsonPrecompile, data, 'name');
console.log('Name:', name); // Output: "Sei Token"

// Or direct extraction with error handling
try {
  const symbolBytes = await jsonPrecompile.extractAsBytes(inputData, 'symbol');
  const symbol = ethers.toUtf8String(symbolBytes);
  console.log('Symbol:', symbol); // Output: "SEI"
} catch (error) {
  console.error('Failed to extract symbol:', error.message);
}
```

### Extract numeric data

```typescript theme={null}
// JSON data with numbers (integers only)
const data = { price: 42, volume: 1000000 };
const inputData = ethers.toUtf8Bytes(JSON.stringify(data));

// Extract integer using safe method
const price = await safeExtractUint256(jsonPrecompile, data, 'price');
console.log('Price:', price.toString()); // Output: "42"

// Handle decimal numbers by using integer representation
const decimalData = { rate: 275 }; // Represents 2.75 with 2 decimal places
const rate = await safeExtractUint256(jsonPrecompile, decimalData, 'rate');
const actualRate = Number(rate) / 100; // Convert to 2.75
console.log('Rate:', actualRate);
```

### Extract array data

```typescript theme={null}
// JSON data with array
const data = { tokens: ['SEI', 'USDC', 'USDT'] };
const inputData = ethers.toUtf8Bytes(JSON.stringify(data));

// Extract array using safe method
const tokens = await safeExtractBytesList(jsonPrecompile, data, 'tokens');
console.log('Tokens:', tokens); // Output: ["SEI", "USDC", "USDT"]

// Handle mixed arrays by extracting as bytes and parsing
const mixedData = { values: [42, 'test', 100] };
const valuesBytes = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(mixedData)), 'values');
const valuesString = ethers.toUtf8String(valuesBytes);
const valuesArray = JSON.parse(valuesString);
console.log('Mixed values:', valuesArray); // Output: [42, "test", 100]
```

### Extract nested data

<Warning>Extract the parent object and parse it manually. The JSON precompile does not support dot notation for nested objects.</Warning>

```typescript theme={null}
// For nested data, extract the parent object first
const data = {
  user: {
    wallet: {
      balance: 1000,
      currency: 'SEI'
    }
  }
};

// Method 1: Extract parent object and parse manually (recommended)
const userBytes = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(data)), 'user');
const userData = JSON.parse(ethers.toUtf8String(userBytes));
const balance = userData.wallet.balance;
const currency = userData.wallet.currency;

console.log('Balance:', balance); // Output: 1000
console.log('Currency:', currency); // Output: "SEI"

// Method 2: Extract deeper nested object
const walletBytes = await jsonPrecompile.extractAsBytes(
  ethers.toUtf8Bytes(JSON.stringify(data)),
  'wallet' // Direct key, not dot notation
);
const walletData = JSON.parse(ethers.toUtf8String(walletBytes));
console.log('Wallet data:', walletData); // Output: { balance: 1000, currency: "SEI" }
```

## Complete integration example

Create a complete JSON parsing application for Sei Mainnet:

```javascript title="json-precompile-mainnet.mjs" theme={null}
// json-precompile-mainnet.mjs
import { ethers } from 'ethers';
import { JSON_PRECOMPILE_ABI, JSON_PRECOMPILE_ADDRESS } from '@sei-js/precompiles';
import 'dotenv/config';

// Safe extraction utilities
async function safeExtractBytes(jsonPrecompile, data, key, defaultValue = '') {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsBytes(inputData, key);
    return ethers.toUtf8String(result);
  } catch (error) {
    console.log(`   ⚠️  Key "${key}" not found, using default: "${defaultValue}"`);
    return defaultValue;
  }
}

async function safeExtractUint256(jsonPrecompile, data, key, defaultValue = 0n) {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsUint256(inputData, key);
    return result;
  } catch (error) {
    console.log(`   ⚠️  Key "${key}" not found or invalid integer, using default: ${defaultValue}`);
    return defaultValue;
  }
}

async function safeExtractBytesList(jsonPrecompile, data, key, defaultValue = []) {
  try {
    const inputData = ethers.toUtf8Bytes(JSON.stringify(data));
    const result = await jsonPrecompile.extractAsBytesList(inputData, key);
    return result.map((bytes) => ethers.toUtf8String(bytes));
  } catch (error) {
    console.log(`   ⚠️  Key "${key}" not found or invalid array, using default: [${defaultValue.join(', ')}]`);
    return defaultValue;
  }
}

async function main() {
  try {
    // Connect to Sei Mainnet
    console.log('🌐 Connecting to Sei Mainnet...');
    const provider = new ethers.JsonRpcProvider('https://evm-rpc.sei-apis.com');

    // Use private key from environment variables (secure approach)
    const privateKey = process.env.PRIVATE_KEY;
    if (!privateKey) {
      throw new Error('Please set PRIVATE_KEY in .env file');
    }

    const wallet = new ethers.Wallet(privateKey, provider);
    console.log(`👤 Wallet address: ${wallet.address}`);

    // Check balance
    const balance = await provider.getBalance(wallet.address);
    const balanceEther = ethers.formatEther(balance);
    console.log(`💰 Wallet balance: ${balanceEther} SEI\n`);

    // Initialize JSON precompile contract
    const jsonPrecompile = new ethers.Contract(JSON_PRECOMPILE_ADDRESS, JSON_PRECOMPILE_ABI, wallet);

    console.log('📄 === Sei Mainnet JSON Precompile Demo ===\n');

    // Complex sample data - simulating a real-world oracle response
    const oracleData = {
      market: {
        prices: {
          SEI: 275, // 2.75 USD (stored as integer with 2 decimal places)
          BTC: 5000000, // 50,000.00 USD
          ETH: 300000 // 3,000.00 USD
        },
        volume: {
          daily: 1500000000, // $15M daily volume
          weekly: 8500000000 // $85M weekly volume
        }
      },
      metadata: {
        timestamp: '2024-12-27T12:00:00Z',
        source: 'MainnetPriceOracle',
        version: '2.1.0',
        isLive: 1 // 1 = true, 0 = false
      },
      assets: ['SEI', 'BTC', 'ETH', 'USDC'],
      validators: {
        active: 125,
        total: 200
      }
    };

    console.log('📋 Input JSON Data:');
    console.log(JSON.stringify(oracleData, null, 2));
    console.log();

    // 1. Extract string data with error handling
    console.log('1️⃣  Extracting String Data...');

    // Extract metadata object first, then parse individual fields
    const metadataBytes = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(oracleData)), 'metadata');
    const metadata = JSON.parse(ethers.toUtf8String(metadataBytes));

    console.log(`   📊 Source: ${metadata.source}`);
    console.log(`   🔢 Version: ${metadata.version}`);
    console.log(`   ⏰ Timestamp: ${metadata.timestamp}`);
    console.log(`   🟢 Is Live: ${metadata.isLive === 1 ? 'Yes' : 'No'}`);

    // Test missing key
    const missingKey = await safeExtractBytes(jsonPrecompile, oracleData, 'nonexistent', 'N/A');
    console.log(`   ❓ Missing Key: ${missingKey}`);

    // 2. Extract numeric data with proper object parsing
    console.log('\n2️⃣  Extracting Numeric Data...');

    // Extract market object first
    const marketBytes = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(oracleData)), 'market');
    const market = JSON.parse(ethers.toUtf8String(marketBytes));

    // Extract validators object
    const validatorsBytes = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(oracleData)), 'validators');
    const validators = JSON.parse(ethers.toUtf8String(validatorsBytes));

    // Convert integers back to decimals
    const seiPrice = market.prices.SEI / 100; // 2 decimal places
    const btcPrice = market.prices.BTC / 100; // 2 decimal places
    const isLive = metadata.isLive === 1; // Convert to boolean

    console.log(`   💰 SEI Price: ${seiPrice} (raw: ${market.prices.SEI})`);
    console.log(`   ₿ BTC Price: ${btcPrice.toLocaleString()} (raw: ${market.prices.BTC})`);
    console.log(`   💹 Daily Volume: ${market.volume.daily.toLocaleString()}`);
    console.log(`   ✅ Active Validators: ${validators.active}`);
    console.log(`   🔴 Is Live: ${isLive} (raw: ${metadata.isLive})`);

    // 3. Extract array data
    console.log('\n3️⃣  Extracting Array Data...');
    const assets = await safeExtractBytesList(jsonPrecompile, oracleData, 'assets');
    const invalidArray = await safeExtractBytesList(jsonPrecompile, oracleData, 'invalid.array', ['DEFAULT']);

    console.log(`   🪙 Assets: [${assets.join(', ')}]`);
    console.log(`   ❌ Invalid Array: [${invalidArray.join(', ')}]`);

    // 4. Extract complex nested objects
    console.log('\n4️⃣  Extracting Complex Nested Data...');
    console.log('   📈 Market Data:');
    console.log(`      Prices: SEI=${market.prices.SEI / 100}, BTC=${market.prices.BTC / 100}, ETH=${market.prices.ETH / 100}`);
    console.log(`      Volume: Daily=${market.volume.daily.toLocaleString()}, Weekly=${market.volume.weekly.toLocaleString()}`);
    console.log(`   👥 Validator Data:`);
    console.log(`      Active: ${validators.active}, Total: ${validators.total}`);

    // 5. Gas optimization demonstration
    console.log('\n5️⃣  Gas Usage Analysis...');
    const gasEstimates = {
      small: 50000, // Simple key extraction
      medium: 80000, // Nested object extraction
      large: 120000 // Complex array/object processing
    };

    console.log('   ⛽ Recommended Gas Limits:');
    console.log(`      Simple extraction: ${gasEstimates.small.toLocaleString()} gas`);
    console.log(`      Nested extraction: ${gasEstimates.medium.toLocaleString()} gas`);
    console.log(`      Complex processing: ${gasEstimates.large.toLocaleString()} gas`);

    // 6. Performance test with corrected key extraction
    console.log('\n6️⃣  Performance & Error Testing...');
    const testCases = [
      { key: 'metadata', expected: 'object', description: 'metadata object' },
      { key: 'market', expected: 'object', description: 'market data' },
      { key: 'assets', expected: 'array', description: 'assets array' },
      { key: 'nonexistent', expected: 'error', description: 'missing key' }
    ];

    for (const testCase of testCases) {
      try {
        const start = Date.now();
        const result = await safeExtractBytes(jsonPrecompile, oracleData, testCase.key);
        const duration = Date.now() - start;
        const preview = result.length > 50 ? result.substring(0, 47) + '...' : result;
        console.log(`   ✅ ${testCase.description}: "${preview}" (${duration}ms)`);
      } catch (error) {
        console.log(`   ❌ ${testCase.description}: ${error.message}`);
      }
    }

    console.log('\n🎉 === JSON Precompile Demo Completed Successfully! ===');
  } catch (error) {
    console.error('\n❌ Error:', error.message);
    console.log('\n🔧 Troubleshooting tips:');
    console.log('1. Ensure PRIVATE_KEY is set in .env file');
    console.log('2. Verify sufficient SEI balance for gas fees');
    console.log('3. Check network connectivity to Sei Mainnet');
    console.log('4. Validate JSON structure before processing');
    process.exit(1);
  }
}

// Run the demo
main().catch(console.error);
```

### Running the mainnet example

1. **Create a new directory and initialize npm:**

```bash theme={null}
mkdir sei-json-mainnet
cd sei-json-mainnet
npm init -y
```

2. **Install dependencies:**

```bash theme={null}
npm install ethers @sei-js/precompiles@^3 dotenv
```

3. **Create a `.env` file:**

```bash theme={null}
PRIVATE_KEY=your_private_key_here
```

<Warning>Never commit private keys to version control. Add the `.env` file to your `.gitignore`.</Warning>

4. **Create the demo file:**
   Copy the complete integration example above into `json-precompile-mainnet.mjs`.

5. **Make sure that you have SEI tokens:**

   * SEI for gas (view functions need only small amounts)

6. **Run the script:**

```bash theme={null}
node json-precompile-mainnet.mjs
```

### Expected output

```
🌐 Connecting to Sei Mainnet...
👤 Wallet address: 0x742d35Cc6634C0532925a3b844Bc6789e065f3B
💰 Wallet balance: 15.5 SEI

📄 === Sei Mainnet JSON Precompile Demo ===

📋 Input JSON Data:
{
  "market": {
    "prices": {
      "SEI": 275,
      "BTC": 5000000,
      "ETH": 300000
    },
    "volume": {
      "daily": 1500000000,
      "weekly": 8500000000
    }
  },
  "metadata": {
    "timestamp": "2024-12-27T12:00:00Z",
    "source": "MainnetPriceOracle",
    "version": "2.1.0",
    "isLive": 1
  },
  "assets": ["SEI", "BTC", "ETH", "USDC"],
  "validators": {
    "active": 125,
    "total": 200
  }
}

1️⃣  Extracting String Data...
   📊 Source: MainnetPriceOracle
   🔢 Version: 2.1.0
   ⏰ Timestamp: 2024-12-27T12:00:00Z
   🟢 Is Live: Yes
   ⚠️  Key "nonexistent" not found, using default: "N/A"
   ❓ Missing Key: N/A

2️⃣  Extracting Numeric Data...
   💰 SEI Price: $2.75 (raw: 275)
   ₿ BTC Price: $50,000 (raw: 5000000)
   💹 Daily Volume: $1,500,000,000
   ✅ Active Validators: 125
   🔴 Is Live: true (raw: 1)

3️⃣  Extracting Array Data...
   🪙 Assets: [SEI, BTC, ETH, USDC]
   ⚠️  Key "invalid.array" not found or invalid array, using default: [DEFAULT]
   ❌ Invalid Array: [DEFAULT]

4️⃣  Extracting Complex Nested Data...
   📈 Market Data:
      Prices: SEI=$2.75, BTC=$50000, ETH=$3000
      Volume: Daily=$1,500,000,000, Weekly=$8,500,000,000

5️⃣  Gas Usage Analysis...
   ⛽ Recommended Gas Limits:
      Simple extraction: 50,000 gas
      Nested extraction: 80,000 gas
      Complex processing: 120,000 gas

6️⃣  Performance & Error Testing...
   ✅ metadata object: "{"timestamp":"2024-12-27T12:00:00Z","source":"..." (15ms)
   ✅ market data: "{"prices":{"SEI":275,"BTC":5000000,"ETH":30000..." (12ms)
   ✅ assets array: "["SEI","BTC","ETH","USDC"]" (18ms)
   ⚠️  Key "nonexistent" not found, using default: ""
   ✅ missing key: "" (8ms)

🎉 === JSON Precompile Demo Completed Successfully! ===
```

## Advanced usage examples

### Oracle price feed integration

```typescript theme={null}
// Advanced oracle integration with comprehensive error handling
class SeiPriceOracle {
  private jsonPrecompile: ethers.Contract;

  constructor(jsonPrecompile: ethers.Contract) {
    this.jsonPrecompile = jsonPrecompile;
  }

  async parsePriceFeed(oracleResponse: any): Promise<{
    prices: Map<string, number>;
    timestamp: string;
    isValid: boolean;
  }> {
    try {
      // The precompile does not support dot notation for nested keys.
      // Extract the parent "metadata" object as bytes, then parse it manually.
      const metadataJson = await safeExtractBytes(this.jsonPrecompile, oracleResponse, 'metadata', '{}');
      const metadata = JSON.parse(metadataJson);
      const timestamp = metadata.timestamp ?? '';
      const isValid = metadata.isLive === 1;

      // Extract the parent "market" object the same way, then read its prices.
      const marketJson = await safeExtractBytes(this.jsonPrecompile, oracleResponse, 'market', '{}');
      const market = JSON.parse(marketJson);
      const rawPrices = market.prices ?? {};

      const prices = new Map<string, number>();
      const assets = await safeExtractBytesList(this.jsonPrecompile, oracleResponse, 'assets');

      for (const asset of assets) {
        // Convert from integer with 6 decimal places
        prices.set(asset, Number(rawPrices[asset] ?? 0) / 1000000);
      }

      return { prices, timestamp, isValid };
    } catch (error) {
      console.error('Failed to parse oracle response:', error);
      return {
        prices: new Map(),
        timestamp: '',
        isValid: false
      };
    }
  }
}
```

## Troubleshooting

### Common issues and solutions

#### Key not found

```typescript theme={null}
// Comprehensive error handling for missing keys
async function handleMissingKeys(jsonPrecompile: ethers.Contract, data: any) {
  const keys = ['required.key', 'optional.key', 'deeply.nested.key'];

  for (const key of keys) {
    try {
      const result = await jsonPrecompile.extractAsBytes(ethers.toUtf8Bytes(JSON.stringify(data)), key);
      console.log(`✅ ${key}: ${ethers.toUtf8String(result)}`);
    } catch (error: any) {
      if (error.message.includes('key not found')) {
        console.log(`⚠️  Key "${key}" not found in JSON structure`);
      } else {
        console.log(`❌ Error extracting "${key}": ${error.message}`);
      }
    }
  }
}
```

### Error code reference

| Error | Cause | Solution |
| - | - | - |
| `key not found` | The specified key does not exist in the JSON | Verify the key path and JSON structure |
| `invalid JSON format` | Malformed JSON input | Use `JSON.stringify()` to make sure the format is valid |
| `execution reverted` | Gas limit too low | Increase the gas limit based on data complexity |
| `invalid integer` | Non-numeric value for `extractAsUint256` | Make sure that the value is a valid integer |
| `out of gas` | Insufficient gas for large JSON | Use `calculateGasLimit()` for dynamic estimation |

## Key considerations and tricks

<Info>
  * **Integers only:** `extractAsUint256` handles only integers. It does not handle decimals, booleans, or negative numbers.
  * **Decimal handling:** Store decimal numbers as integers with known precision. For example, use 275 for 2.75 with 2 decimal places.
  * **Boolean values:** Use the integer 0 for false and 1 for true.
  * **Key paths:** Extract parent objects first, then parse them manually. Dot notation may not be supported.
  * **Arrays:** Object-keyed arrays use `extractAsBytesList()`. JSON arrays by index use `extractAsBytesFromArray()`.
  * **Gas costs:** Large JSON objects need higher gas limits.
  * **Encoding:** Always use UTF-8 encoding with `ethers.toUtf8Bytes()`.
  * **Error handling:** Always implement fallback values for production applications.
</Info>

<Info>**Need help?** If you have a problem that this page does not cover, look for community support in the [Sei Discord](https://discord.gg/sei) or the [GitHub repository](https://github.com/sei-protocol/sei-chain).</Info>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.