PHP Array to JSON

Paste a PHP array, in short [] syntax or the old array() form, and get JSON. A JavaScript parser reads the literal and nothing is executed, so you can convert a snippet from a private codebase without running it or pasting it into an online PHP sandbox.

PHP Array Input
JSON Output

1 PHP Array to JSON example

PHP Array Input

1
2
3
4
5
6
7
[
    'id' => 1,
    'name' => 'John Doe',
    'role' => 'Admin',
    'active' => true,
    'skills' => ['PHP', 'JavaScript', 'SQL']
]

JSON Output

1
2
3
4
5
6
7
8
9
10
11
{
  "id": 1,
  "name": "John Doe",
  "role": "Admin",
  "active": true,
  "skills": [
    "PHP",
    "JavaScript",
    "SQL"
  ]
}

2 Why do it here

No PHP required

The array literal is parsed in JavaScript in this tab, so you need neither a local PHP install nor a remote sandbox to convert a snippet.

Old and new syntax

Both array() and [] parse, nested or mixed, which matters in codebases with a long history. However, any explicit key produces a JSON object, so the numbered lists that var_export() prints come out as objects with keys "0", "1" and so on.

How to use the PHP Array to JSON tool

  1. Paste a PHP array into the left editor, or load one with Upload PHP or Load URL. Dummy Data drops in a sample.
  2. Both array( ... ) and [ ... ] syntax are accepted. Paste the bare array; a trailing semicolon is fine, but remove any $data = prefix, or the output is just the string "$data".
  3. JSON appears on the right as you type. A list without keys gives a JSON array, and a single key => value pair turns the result into an object.
  4. The parser only understands literals. If it fails, or a value comes out as a name such as "PHP_EOL", replace constants, variables and function calls with their values.
  5. Click Copy JSON to copy the result.

How to convert a PHP array to JSON with json_encode

PHP

<?php
$config = [
    'name'    => 'My App',
    'debug'   => false,
    'hosts'   => ['a.example.com', 'b.example.com'],
    'limits'  => ['rate' => 100, 'burst' => 20],
    'path'    => '/var/www/app',
    'empty'   => [],
];

echo json_encode(
    $config,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
);

JSON_UNESCAPED_SLASHES stops / becoming \/ and JSON_UNESCAPED_UNICODE keeps é instead of \u00e9. JSON_THROW_ON_ERROR needs PHP 7.3.

Command line

# config.php ends with:  return [ ... ];
php -r 'echo json_encode(include "config.php", JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;'

# Or pipe it into a file
php -r 'echo json_encode(include "config.php", JSON_PRETTY_PRINT);' > config.json

Works for any file that returns an array, Laravel's config/*.php included, as long as the file does not lean on the framework.

Common errors and how to fix them

json_encode() returns false
Usually a string that is not valid UTF-8, for example Latin-1 data from a database. Check json_last_error_msg(). Fix the encoding with mb_convert_encoding(), or pass JSON_INVALID_UTF8_SUBSTITUTE.
An empty array becomes [] when the API expects {}
PHP cannot tell an empty list from an empty map. Cast it: (object) [] or new stdClass, or pass JSON_FORCE_OBJECT to make every array an object.
A list becomes an object with keys "0", "1", "3"
The integer keys are not sequential from zero, often after unset() or array_filter(). Call array_values() before encoding.
Floats print as 0.30000000000000004 or 1.0E+25
json_encode uses serialize_precision, which defaults to -1 (shortest round-trip form). Round the value with round($x, 2) before encoding if you need fixed decimals.
Private and protected properties are missing from encoded objects
json_encode only sees public properties. Implement JsonSerializable and return the array you want from jsonSerialize().

Good to know

json_encode() picks array or object with one rule: keys 0 to n-1 in order mean array, anything else means object. That rule explains most of the array_values() and JSON_FORCE_OBJECT calls you see in bug reports. This tool uses a simpler rule, so [0 => 'a'] comes out as an object here and as a list from json_encode(). The difference matters because strict consumers, TypeScript clients and JSON Schema validators among them, reject the wrong one.

By default json_encode escapes slashes and every non-ASCII character. That is a leftover from embedding JSON inside HTML script tags. The output is valid, but harder to read and bigger than it needs to be, and JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE fixes both. Save JSON_HEX_TAG and friends for the case they were built for: JSON inside an HTML attribute.

Specifications and references

This tool follows the specifications below. Read them when you need the exact normative wording, for example to settle an edge case between two implementations.

Guides and tutorials

Frequently Asked Questions

Which PHP array syntaxes are accepted?

Both the classic array( ... ) form and the short [ ... ] form, including nested arrays, string and integer keys and the => operator. Comments written with // or /* */ are skipped.

How are associative and indexed arrays converted?

A list without explicit keys, such as ['a', 'b'], becomes a JSON array. Any key => value pair makes the result a JSON object, even [0 => 'a', 1 => 'b'], where json_encode() would produce a list. Remove the numeric keys if you want an array.

Can I paste the output of var_export()?

Yes, it parses. However, var_export() writes every list with explicit numeric keys, so those lists come out as objects with keys "0", "1" and so on. print_r() output is not PHP syntax and will not parse.

Are PHP constants or variables supported?

No. The parser reads literal values only: strings, numbers, booleans, null and nested arrays. A constant such as PHP_EOL is copied into the JSON as the string "PHP_EOL", so replace constants and variables with their values first.

Why would I use this instead of json_encode()?

Use it when you have no PHP runtime at hand: converting a config file for a JavaScript project, documenting an API, or moving data between languages. Inside a PHP project, json_encode() is the right call.

Related

JSON to PHP array converts in the other direction. PHP array to CSV is the spreadsheet route, and PHP array to Table renders the array as a table.

More Data Converters

Browse all data converters

Copied to clipboard!