## `parseJson`

### Signature

```solidity
function parseJson(string memory json, string memory key) external pure returns (bytes memory);
function parseJson(string memory json) external pure returns (bytes memory);
```

### Description

Parses JSON files in the form of strings. Usually coupled with `vm.readFile()` which returns an entire file in the form of a string.

The cheatcode accepts either a `key` to search for a specific value in the JSON, or no key to return the entire JSON. It returns the value as an ABI-encoded `bytes` array that must be decoded with `abi.decode()`.

You can use `stdJson` from `forge-std` as a helper library for better UX.

### Parameters

| Parameter | Type     | Description                                |
|-----------|----------|--------------------------------------------|
| `json`    | `string` | The JSON string to parse                   |
| `key`     | `string` | The JSONPath key to retrieve (optional)    |

### Returns

| Type    | Description                                |
|---------|--------------------------------------------|
| `bytes` | The ABI-encoded value(s) from the JSON     |

### JSONPath Key Syntax

`parseJson` uses JSONpath syntax to form arbitrary keys for arbitrary JSON files. The same syntax (or a dialect) is used by [`jq`](https://stedolan.github.io/jq/).

See the [jsonpath-rust README](https://crates.io/crates/jsonpath-rust) for the exact dialect used.

### JSON Encoding Rules

We use the terms `number`, `string`, `object`, `array`, `boolean`, `null` as defined in the [JSON spec](https://www.w3schools.com/js/js_json_datatypes.asp).

| JSON Type | Solidity Type |
|-----------|---------------|
| `null` | `bytes32(0)` |
| Number >= 0 | `uint256` |
| Negative number | `int256` |
| String starting with `0x` (40 hex chars) | `address` |
| String starting with `0x` (66 chars) | `bytes32` |
| String starting with `0x` (other lengths) | `bytes` |
| Other strings | `string` |
| Array | Dynamic array of first element's type |
| Object (`{}`) | `tuple` |

:::warning
Floating point numbers with decimal digits are not allowed. Use scientific notation for large numbers.
:::

### Type Coercion

For more control, use typed parsing functions that coerce values:

```solidity
vm.parseJsonUint(json, key)      // Parse as uint256
vm.parseJsonInt(json, key)       // Parse as int256
vm.parseJsonBool(json, key)      // Parse as bool
vm.parseJsonAddress(json, key)   // Parse as address
vm.parseJsonBytes(json, key)     // Parse as bytes
vm.parseJsonBytes32(json, key)   // Parse as bytes32
vm.parseJsonString(json, key)    // Parse as string
vm.parseJsonUintArray(json, key) // Parse as uint256[]
// ... and more array variants
```

These can parse hex strings, stringified numbers, and regular values into the target type.

### Examples

#### Decoding JSON objects into Solidity structs

JSON objects are encoded as tuples and can be decoded into structs:

:::code-group
```solidity [test/ParseJson.t.sol]
struct Data {
    uint256 a;
    string b;
}

function test_parseJson() public {
    string memory json = vm.readFile("./fixtures/example.json");
    bytes memory data = vm.parseJson(json);
    Data memory result = abi.decode(data, (Data));
    assertEq(result.a, 43);
    assertEq(result.b, "sigma");
}
```

```json [fixtures/example.json]
{
  "a": 43,
  "b": "sigma"
}
```
:::

:::warning[Alphabetical Ordering]
Struct fields are matched to JSON keys in **alphabetical order by key name**, not by struct field order. Ensure your struct field types match the alphabetically-sorted JSON keys.
:::

:::note
Uppercase characters precede lowercase in the lexicographical ordering (e.g., "Zebra" precedes "apple").
:::

#### Complex nested structures

:::code-group
```solidity [test/ParseJson.t.sol]
struct Apple {
    string color;    // 'c' comes first alphabetically
    uint8 sourness;  // 's' comes second
    uint8 sweetness; // 's' - but 'sourness' < 'sweetness'
}

struct FruitStall {
    Apple[] apples;  // 'a' comes before 'n'
    string name;
}

function test_parseNestedJson() public {
    string memory root = vm.projectRoot();
    string memory path = string.concat(root, "/fixtures/fruitstall.json");
    string memory json = vm.readFile(path);
    bytes memory data = vm.parseJson(json);
    FruitStall memory fruitstall = abi.decode(data, (FruitStall));
    
    console2.log("Welcome to", fruitstall.name);
}
```

```json [fixtures/fruitstall.json]
{
  "apples": [
    { "sweetness": 7, "sourness": 3, "color": "Red" },
    { "sweetness": 5, "sourness": 5, "color": "Green" }
  ],
  "name": "Fresh Fruit"
}
```
:::

### How to use StdJson

1. Import the library: `import {stdJson} from "forge-std/StdJson.sol";`
2. Define its usage: `using stdJson for string;`
3. Use helper functions for simple values or `parseRaw()` for entire objects

```solidity [test/StdJsonExample.t.sol]
using stdJson for string;

function test_stdJson() public {
    string memory root = vm.projectRoot();
    string memory path = string.concat(root, "/fixtures/broadcast.log.json");
    string memory json = vm.readFile(path);
    bytes memory transactionDetails = json.parseRaw(".transactions[0].tx");
    RawTx1559Detail memory rawTxDetail = abi.decode(transactionDetails, (RawTx1559Detail));
}
```

### Gotchas

:::warning[File Permissions]
If you receive "The path is not allowed to be accessed for read operations", enable read permissions in `foundry.toml`:

```toml
fs_permissions = [{ access = "read", path = "./fixtures" }]
```
:::

:::tip[Hex Numbers in JSON]
If your JSON has hex numbers, they'll be encoded as bytes. Create an intermediary struct with `bytes` fields, decode to it, then convert to your final struct with `uint` fields.
:::

### Related Cheatcodes

* [`parseToml`](/reference/cheatcodes/parse-toml) - Parse TOML files
* [`parseJsonKeys`](/reference/cheatcodes/parse-json-keys) - Get list of keys
* [`keyExistsJson`](/reference/cheatcodes/key-exists-json) - Check if key exists
* [`serializeJson`](/reference/cheatcodes/serialize-json) - Serialize values to JSON

### See Also

* [stdJson.sol](https://github.com/foundry-rs/forge-std/blob/master/src/StdJson.sol)
* [File Cheatcodes](/reference/cheatcodes/fs)
