Skip to content
StringToJSON

PHP — String to JSON

Convert a string to JSON in PHP.

json_decode converts a JSON string to an array or object; json_encode converts it back. Verify your payload with the free online converter above, then use the pattern below.

Escaped string

0 B

JSON

0 B

Output appears here.

Ready. Paste something above.

Everything runs locally in your browser — your data never leaves this page. Press⌘/Ctrl +Enter to run.

The second argument decides everything

$json = '{"id": 42, "name": "Ada", "tags": ["a", "b"]}';

$obj = json_decode($json);          // stdClass
echo $obj->name;                    // Ada

$arr = json_decode($json, true);    // associative array
echo $arr['name'];                  // Ada
echo $arr['tags'][0];               // a

$back = json_encode($arr);          // array -> JSON string

Most PHP code wants the array form, which means remembering that true. Forgetting it produces a stdClass, and the mismatch shows up later asTrying to access array offset on value of type object.

Failures are silent by default

$data = json_decode($json, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Bad JSON: ' . json_last_error_msg());
}

// PHP 7.3+ — much better
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

json_decode returns null on failure — and null is also the correct result for the valid input "null", so the return value alone cannot tell you whether parsing worked. Use JSON_THROW_ON_ERROR on any modern version and stop thinking about it.

Encoding flags worth knowing

json_encode($data,
      JSON_PRETTY_PRINT
    | JSON_UNESCAPED_SLASHES
    | JSON_UNESCAPED_UNICODE
    | JSON_THROW_ON_ERROR
);
  • JSON_PRETTY_PRINT — indented output for files and logs.
  • JSON_UNESCAPED_SLASHES — keeps URLs readable instead of http:\/\/.
  • JSON_UNESCAPED_UNICODE — keeps accented characters and emoji as themselves.
  • JSON_PRESERVE_ZERO_FRACTION — writes 1.0 rather than 1.

Sequential versus associative

PHP has one array type doing two jobs, and json_encode has to guess which you meant. An array with keys 0, 1, 2… in order becomes a JSON array; anything else becomes an object. This bites after filtering: array_filter preserves keys, so removing element1 leaves [0 => …, 2 => …] and your list silently encodes as{"0":…,"2":…}. Run the result through array_values() before encoding and the problem disappears.

The other classic is Array to string conversion, a warning rather than an error, which means an array reached a string context — usually an echo or a concatenation that needed json_encode around it first.

Large numbers and precision

JSON does not distinguish integers from floats, and PHP's decoder has to guess. Any integer larger than PHP_INT_MAX silently becomes a float, which quietly destroys long IDs — a 19-digit Twitter or Snowflake identifier comes back rounded and no longer matches anything. Pass the JSON_BIGINT_AS_STRING flag to keep such values as strings, and treat IDs as strings throughout rather than casting them back.

The reverse problem appears on encode: a float that happens to hold a whole number is written as1 rather than 1.0, so a consumer expecting a decimal sees an integer.JSON_PRESERVE_ZERO_FRACTION fixes that when the distinction matters, which it does for money and for APIs with strict schemas.

Depth limits and recursion

Both functions take a depth argument that defaults to 512. Exceeding it returns nullfrom json_decode and false from json_encode — another silent failure unless you are checking json_last_error() or throwing. You will hit it far sooner with circular references: an object graph that points back at itself recurses until the limit stops it. Break the cycle before encoding, or implementJsonSerializable on the class and return a flat representation fromjsonSerialize(). That interface is also the cleanest way to control how your domain objects appear in an API response, rather than exposing whatever properties happen to be public.

Naming, briefly

String to JSON in PHP, python string to json online, PHP convert JSON string to array, json string to array php, and json string to php array are the same call with true as the second argument. The reverse — php array to json string — is json_encode. Only the "Array to string conversion in PHP json" warning is something different: that is PHP telling you an array reached a string context without being encoded first. Use the free online string to JSON tool above to validate any payload before passing it to json_decode.

Frequently asked questions

How to convert a JSON string to an array in PHP?
Call json_decode($json, true). The second argument is the important one — passing true returns an associative array, while leaving it out returns a stdClass object.
Why does json_decode return null?
The input is not valid JSON. json_decode returns null instead of throwing, so failures pass silently. Check json_last_error_msg(), or pass the JSON_THROW_ON_ERROR flag so you get a JsonException instead.
What causes "Array to string conversion"?
You used an array where PHP expected a string — echoing it, concatenating it, or interpolating it into a query. Wrap it in json_encode() first. This notice never comes from json_decode itself.
Why do my slashes come out as \/ ?
json_encode escapes forward slashes by default. It is valid JSON either way, but for readability pass JSON_UNESCAPED_SLASHES — usually together with JSON_UNESCAPED_UNICODE, which stops accented characters becoming \uXXXX.
How do I convert a PHP array to a JSON string?
json_encode($array). A sequential array becomes a JSON array; an associative array becomes a JSON object. Add JSON_PRETTY_PRINT for indented output.