What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 [IST]"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 [IST]"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 [IST]"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 [IST]"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 [IST]"
}]
}
Use json_decode
to convert String into Object [stdClass
] or array: //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:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 [IST]"}]}';
You should convert it to Object [stdClass]:
$manage = json_decode[$data];
But working with stdClass
is more complicated than PHP-Array, then try this [use second param with true
]:
$manage = json_decode[$data, true];
This way you can use array functions: //php.net/manual/en/function.array.php
adding an item:
$manage = json_decode[$data, true];
echo 'Before:
';
print_r[$manage];
$manage['Coords'][] = Array[
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 [IST]'
];
echo '
After:
';
print_r[$manage];
remove first item:
$manage = json_decode[$data, true];
echo 'Before:
';
print_r[$manage];
array_shift[$manage['Coords']];
echo '
After:
';
print_r[$manage];
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 [IST]"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 [IST]"}]}';
$manage = json_decode[$data, true];
$manage['Coords'][] = Array[
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 [IST]'
];
if [[$id = fopen['datafile.txt', 'wb']]] {
fwrite[$id, json_encode[$manage]];
fclose[$id];
}
I hope I have understood your question.
Good luck.
[PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0]
json_decode — Decodes a JSON string
Description
json_decode[
string $json
,
?bool $associative
=
null
,
int $depth
= 512,
int $flags
= 0
]: mixed
Parameters
json
The json
string being decoded.
This function only works with UTF-8 encoded strings.
Note:
PHP implements a superset of JSON as specified in the original » RFC 7159.
associative
When true
, JSON objects will be returned as associative arrays; when false
, JSON objects will be returned as
objects. When null
, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY
is set in the flags
.
depth
Maximum nesting depth of the structure being decoded. The value must be greater than 0
, and less than or equal to 2147483647
.
flags
Bitmask of JSON_BIGINT_AS_STRING
, JSON_INVALID_UTF8_IGNORE
,
JSON_INVALID_UTF8_SUBSTITUTE
, JSON_OBJECT_AS_ARRAY
, JSON_THROW_ON_ERROR
. The behaviour of these constants is described on the JSON constants page.
Return Values
Returns the value encoded in json
in appropriate PHP type. Values true
, false
and null
are returned as
true
, false
and null
respectively. null
is returned if the json
cannot be decoded or if the encoded data is deeper than the nesting limit.
Errors/Exceptions
If depth
is outside the allowed range, a ValueError is thrown as of PHP 8.0.0,
while previously, an error of level E_WARNING
was raised.
Changelog
7.3.0 | JSON_THROW_ON_ERROR flags was added.
|
7.2.0 | associative is nullable now.
|
7.2.0 | JSON_INVALID_UTF8_IGNORE , and JSON_INVALID_UTF8_SUBSTITUTE flags were added.
|
7.1.0 | An empty JSON key [""] can be encoded to the empty object property instead of using a key with value _empty_ .
|
Examples
Example #1 json_decode[] examples
The above example will output:
object[stdClass]#1 [5] { ["a"] => int[1] ["b"] => int[2] ["c"] => int[3] ["d"] => int[4] ["e"] => int[5] } array[5] { ["a"] => int[1] ["b"] => int[2] ["c"] => int[3] ["d"] => int[4] ["e"] => int[5] }
Example #2 Accessing invalid object properties
Accessing elements within an object that contain characters not permitted under PHP's naming convention [e.g. the hyphen] can be accomplished by encapsulating the element name within braces and the apostrophe.
Example #3 common mistakes using json_decode[]
Example #4 depth
errors
The above example will output:
array[1] { [1]=> array[2] { ["English"]=> array[2] { [0]=> string[3] "One" [1]=> string[7] "January" } ["French"]=> array[2] { [0]=> string[3] "Une" [1]=> string[7] "Janvier" } } } Last error: No error NULL Last error: Maximum stack depth exceeded
Example #5 json_decode[] of large integers
The above example will output:
object[stdClass]#1 [1] { ["number"]=> float[1.2345678901235E+19] } object[stdClass]#1 [1] { ["number"]=> string[20] "12345678901234567890" }
Notes
Note:
The JSON spec is not JavaScript, but a subset of JavaScript.
Note:
In the event of a failure to decode, json_last_error[] can be used to determine the exact nature of the error.
See Also
- json_encode[] - Returns the JSON representation of a value
- json_last_error[] - Returns the last error occurred
Lennart Hengstmengel ¶
8 months ago
JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a "list" or "object" when converted to/from JSON, depending on the keys [of absence of them].
You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:
$json = '{"0": "No", "1": "Yes"}';
$array = json_decode[$json, true]; // decode as associative hash
print json_encode[$array] . PHP_EOL;
This will output a different JSON string than the original:
["No","Yes"]
The object has turned into an array!
Similarly, a array that doesn't have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.
$array = [
'first',
'second',
'third',
];
print json_encode[$array] . PHP_EOL;
// remove the second element
unset[$array[1]];
print json_encode[$array] . PHP_EOL;
The output will be:
["first","second","third"]
{"0":"first","2":"third"}
The array has turned into an object!
In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!
On the other hand, decoding/encoding from/to stdClass objects [the default] is always symmetrical.
Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.
If you want to enforce an array to encode to a JSON list [all array keys will be discarded], use:
json_encode[array_values[$array]];
If you want to enforce an array to encode to a JSON object, use:
json_encode[[object]$array];
See also: //www.php.net/manual/en/function.array-is-list.php
Alien426 ¶
1 year ago
Browsers don't choke on integers _starting_ with BigInt [64 bits], but before that [53 bits]. The introduction of BigInt to modern browsers doesn't help much, when JSON handling functions do not support it. So I am trying to remedy that. My approach is to handle the decoded array before re-encoding it to a string:
cubefox at web dot NOSPAMPLEASE dot de ¶
1 year ago
Warning: As the section "return values" mentions, the return value NULL is ambiguos. To repeat, it can mean three things:
* The input string had the value "null"
* There was an error while parsing the input data
* The encoded data was deeper than the recursion limit
To distinguish these cases, json_last_error[] can be used.
greaties at ghvernuft dot nl ¶
1 year ago
To load an object with data in json format:
function loadJSON[$Obj, $json]
{
$dcod = json_decode[$json];
$prop = get_object_vars [ $dcod ];
foreach[$prop as $key => $lock]
{
if[property_exists [ $Obj , $key ]]
{
if[is_object[$dcod->$key]]
{
loadJSON[$Obj->$key, json_encode[$dcod->$key]];
}
else
{
$Obj->$key = $dcod->$key;
}
}
}
}
as-works at narod dot ru ¶
10 months ago
On some PHP7+ systems php_json functions can be undefined [i faced it on Oracle Linux Enterprice with php 7.4 installed from REMI repository]. If you have the same problem, try to install separated php-json module:
# yum install php-json
Hope this helps.
Anonymous ¶
1 year ago
Which is inline with the above mentioned docs/spec Considering that the 1st arg was a sequentially encoded array as a json string
The above will output
Considering one might expect
an stdClass object instead of an array, but this is incorrect.
json_decode will always return an array for a sequentially encoded array, regardless of the ?bool $associative 2nd argument
> Returns the value encoded in json in appropriate PHP type
'["foo","bar",["baz"]]'
mattia ¶
1 year ago
if you're using ajax to post, and your JavaScript code looks like this:
var xhttp = new XMLHttpRequest[];
xhttp.open["POST", "something.php", true];
xhttp.setRequestHeader["Content-Type", "application/json"];
xhttp.onreadystatechange = function[] {
if [this.readyState == 4 && this.status == 200] {
// do something
}
};
var data = {some: "thing"};
xhttp.send[JSON.stringify[data]];
then in
something.php
you can retrieve your json by doing