php string to json string
json_encode
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)
json_encode — Returns the JSON representation of a value
Description
The encoding is affected by the supplied flags and additionally the encoding of float values depends on the value of serialize_precision.
Parameters
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
PHP implements a superset of JSON as specified in the original » RFC 7159.
Set the maximum depth. Must be greater than zero.
Return Values
Returns a JSON encoded string on success or false on failure.
Changelog
Examples
Example #1 A json_encode() example
The above example will output:
Example #2 A json_encode() example showing some flags in use
The above example will output:
Example #3 JSON_NUMERIC_CHECK option example
The above example will output something similar to:
Example #4 Sequential versus non-sequential array example
The above example will output:
Example #5 JSON_PRESERVE_ZERO_FRACTION option example
The above example will output:
Notes
In the event of a failure to encode, json_last_error() can be used to determine the exact nature of the error.
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
See Also
User Contributed Notes 39 notes
This isn’t mentioned in the documentation for either PHP or jQuery, but if you’re passing JSON data to a javascript program, make sure your program begins with:
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?
Just watch this usecase:
// International phone number
json_encode (array( ‘phone_number’ => ‘+33123456789’ ), JSON_NUMERIC_CHECK );
?>
And then you get this JSON:
Maybe it makes sense for PHP (as is_numeric(‘+33123456789’) returns true), but really, casting it as an int?!
So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.
SOLUTION: Use array_values() to re-index the array.
This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):
I came across the «bug» where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.
You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.
Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.
Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.
PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn’t used, you’d never notify it’s nulled)
If you are planning on using this function to serve a json file, it’s important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add «;» to the end.
It took me a while to figure this out so I thought I’d save others the aggravation.
( ‘Content-Type: text/javascript; charset=utf8’ );
header ( ‘Access-Control-Allow-Origin: http://www.example.com/’ );
header ( ‘Access-Control-Max-Age: 3628800’ );
header ( ‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE’ );
This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).
Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:
In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
«data»: [
In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
«data: [],
This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.
This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).
Solution for UTF-8 Special Chars.
If you need to force an object (ex: empty array) you can also do:
Be careful with floating values in some locales (e.g. russian) with comma («,») as decimal point. Code:
Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like «LC_NUMERIC, ‘en_US.utf8′» before using json_encode.
Here is a bit more on creating an iterator to get at those pesky private/protected variables:
class Kit implements IteratorAggregate <
If I want to encode object whith all it’s private and protected properties, then I implements that methods in my object:
Found that much more simple than regular expressions with PHP serialized objects.
For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn’t want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.
I don’t make a claim that this function is by any means complete (for example, it doesn’t handle objects) so if you have any improvements, go for it.
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
json_decode
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)
json_decode — Декодирует строку JSON
Описание
Принимает закодированную в JSON строку и преобразует её в переменную PHP.
Список параметров
Строка ( string ) json для декодирования.
Эта функция работает только со строками в кодировке UTF-8.
PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.
Максимальная глубина вложенности структуры, для которой будет производиться декодирование.
Возвращаемые значения
Список изменений
Примеры
Пример #1 Примеры использования json_decode()
Результат выполнения данного примера:
Пример #2 Доступ к свойствам объектов с неправильными именами
Доступ к элементам объекта, которые содержат символы, недопустимые в соответствии с соглашением об именах PHP (то есть дефис), может быть выполнен путём обрамления имени элемента фигурными скобками и апострофами.
Пример #3 Распространённая ошибка при использовании json_decode()
// Следующие строки являются валидным кодом JavaScript, но не валидными JSON-данными
Пример #4 Ошибки с глубиной вложенных объектов ( depth )
Результат выполнения данного примера:
Пример #5 json_decode() с большими целыми числами
Результат выполнения данного примера:
Примечания
В случае возникновения ошибки декодирования можно использовать json_last_error() для определения её причины.
Смотрите также
How to convert a string to JSON object in PHP
I have the following result from an SQL query:
It is currently a string in PHP. I know it’s already in JSON form, is there an easy way to convert this to a JSON object?
I need it to be an object so I can add an extra item/element/object like what «Coords» already is.
4 Answers 4
What @deceze said is correct, it seems that your JSON is malformed, try this:
Use json_decode to convert String into Object ( stdClass ) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by «an official JSON object», but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
You should convert it to Object (stdClass):
But working with stdClass is more complicated than PHP-Array, then try this (use second param with true ):
$manage = json_decode($data, true);
adding an item:
remove first item:
any chance you want to save to json to a database or a file:
I hope I have understood your question.
To convert a valid JSON string back, you can use the json_decode() method.
To convert it back to an object use this method:
And to convert it to a associative array, set the second parameter to true :
By the way to convert your mentioned string back to either of those, you should have a valid JSON string. To achieve it, you should do the following:
(PHP 5 >= 5.2.0, PECL json >= 1.2.0, PHP 7)
json_decode — Декодирует JSON строку
Описание
Принимает закодированную в JSON строку и преобразует ее в переменную PHP.
Список параметров
json строка ( string ) для декодирования.
Эта функция работает только со строками в UTF-8 кодировке.
И хотя это надмножество согласуется с расширенным определением «JSON текста» из новых » RFC 7159 (который старается заменить собой RFC 4627) и » ECMA-404, это все равно может приводить к проблемам совместимости со старыми парсерами JSON, которые строго придерживаются RFC 4627 с кодированием скалярных значений.
Указывает глубину рекурсии.
Битовая маска опций декодирования JSON. В настоящий момент поддерживается только JSON_BIGINT_AS_STRING (по умолчанию большие целые числа приводятся к числам с плавающей запятой (float))
Возвращаемые значения
Примеры
Пример #1 Пример использования json_decode()
Результат выполнения данного примера:
Пример #2 Доступ к свойствам объектов с неправильными именами
Доступ к элементам объекта, которые содержат символы недопустимые согласно соглашению об именах PHP (т.е. дефис), может производиться путем обрамления имени элемента фигурными скобками и апострофами.
Пример #3 Распространенная ошибка при использовании json_decode()
// Следующие строки являются валидным кодом JavaScript, но не валидными JSON данными
Пример #4 Ошибки с глубиной вложенных объектов ( depth )
Результат выполнения данного примера:
Пример #5 json_decode() с большими целыми числами
Результат выполнения данного примера:
Примечания
Спецификация JSON не тоже самое, что и JavaScript, но является его частью.
В случае ошибки декодирования можно использовать json_last_error() для определения ее причины.