php json decode string
(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() для определения ее причины.
Список изменений
Смотрите также
How to decode a JSON String with several objects in PHP?
I know how to decode a JSON string with one object with your help from this example How to decode a JSON String
But now I would like to improve decoding JSON string with several objects and I can’t understand how to do it.
Here is an example:
2 Answers 2
New answer
Re your revised question: foreach actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:
Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a «firstName» property, this code:
Old answer(s)
Begin edit Re your comment:
Now I would like to know how to decode JSON string with several objects!
The example you posted does have several objects, they’re just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:
That JSON is not valid. There has to be a single top-level object. It might just contain an array:
. or of course you can give the individual objects names:
End edit
Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it’s not much different from the example in the question you linked (which also has an object with properties that have array values).
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() для определения её причины.
Смотрите также
PHP json_decode integers and floats to string
I want to pre-parse a json an convert all numbers in the json (integers or float) to strings.
Update I have found the following but it does not work for floats:
Update 2 Fixed second float value. It had two points.
6 Answers 6
Use JSON_BIGINT_AS_STRING option:
json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING)
Use this: It should work
I like this is solution for big float:
This is code replace only float to string and you should use it before call json_decode()
Here is a regex which works on float numbers, and it works for attributes, but also arrays. It also works for negative floats.
If you also want to cover for scientific notations, this will work but this will also convert integers to strings
The inspiration was taken from this answer, i’ve adjusted the regex to be even able to use replace, and expanded it to work with arrays and negatives https://stackoverflow.com/a/35008486
Issues
This will fail if there is whitespace in the json (which in production environment is never the case). If you have whitespace then you could just remove all whitespace with this (but if you have sentences anywhere in the json, this will merge it into a single long word)
Another issue with this approach is that the array matches are not safe if they are found within a string. These will be rare, but they still might happen.
This will also fail
Unfortunately there is no straightforward way of getting around these limitations using only one regex pass. However, if you have a response that contains purely numbers, then this works like a charm!
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: