# JsonFormatter

> Formats JSON while retaining selected empty containers as arrays.

[API reference](/docs/api/index.md) › [Foxy](/docs/extensions/foxy/reference/index.md) › [Json](/docs/extensions/foxy/reference/json/index.md) › JsonFormatter

| final class | `Foxy\Json\JsonFormatter` |
| --- | --- |
| Source | [`src/Json/JsonFormatter.php`](https://github.com/php-forge/foxy/blob/main/src/Json/JsonFormatter.php#L22) |

Formats JSON while retaining selected empty containers as arrays.

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`format()`](#method-format) static | Format the data in JSON. | `JsonFormatter` |
| [`getArrayKeys()`](#method-getArrayKeys) static | Get the list of keys to be retained with an array representation if they are empty. | `JsonFormatter` |
| [`getMapKeys()`](#method-getMapKeys) static | Get the keys that were represented as empty JSON objects. | `JsonFormatter` |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-ARRAY_KEYS_REGEX"></span>`ARRAY_KEYS_REGEX` | `'/["\']([\w\-.]+)["\']\s*:\s*\[\s*]/'` |  | `JsonFormatter` |
| <span id="const-DEFAULT_INDENT"></span>`DEFAULT_INDENT` | `4` |  | `JsonFormatter` |
| <span id="const-MAP_KEYS_REGEX"></span>`MAP_KEYS_REGEX` | `'/["\']([\w\-.]+)["\']\s*:\s*\{\s*}/'` |  | `JsonFormatter` |

## Method details

### format() <span id="method-format"></span>

```php
public static function format(string $json, string[] $arrayKeys = [], int $indent = \self::DEFAULT_INDENT, bool $formatJson = true): string
```

Format the data in JSON.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$json` | `string` | The original JSON. |
| `$arrayKeys` | `string[]` | The list of keys to be retained with an array representation if they are empty. |
| `$indent` | `int` | The space count for indent. |
| `$formatJson` | `bool` | Check if the JSON must be formatted. |

**Returns**

`string`

**Throws**

- [`JsonException`](https://www.php.net/manual/en/class.jsonexception.php): if the JSON cannot be decoded or encoded.

### getArrayKeys() <span id="method-getArrayKeys"></span>

```php
public static function getArrayKeys(string $content): array
```

Get the list of keys to be retained with an array representation if they are empty.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$content` | `string` | The content. |

**Returns**

`array`

### getMapKeys() <span id="method-getMapKeys"></span>

```php
public static function getMapKeys(string $content): array
```

Get the keys that were represented as empty JSON objects.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$content` | `string` |  |

**Returns**

`array`