I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);
Related
The question
I have a JSON string which I would like to decode. However, I only want the first level to be decoded, the rest of the JSON should stay as string values instead of nested arrays.
Using a similar technique, the generated array (with nested string values) should be parsed back to a JSON string. When using these decode and encode in succession the result should be the original JSON string.
Short and simple, right?
I would also rather not interpret the nested values of the JSON, as those may or may not be valid JSON. If there is no way around this, then so be it.
Example
Please note that all these slashes are just to keep it a valid PHP string, they are not part of the input. There are no escaped quotes in the input.
When a JSON string like this is put in:
"{
\"foo\": \"bar\",
\"nested\": {
\"nested_key\": \"nested_value\"
},
\"another_top_level_key\": \"some_useful_value\"
}"
This should be the output:
[
"foo" => "bar",
"nested" => "{ \"nested_key\": \"nested_value\" }",
"another_top_level_key" => "some_useful_value"
]
When using var_dump, it should look like this:
array(3) {
["foo"]=>
string(3) "bar"
["nested"]=>
string(32) "{ "nested_key": "nested_value" }"
["another_top_level_key"]=>
string(17) "some_useful_value"
}
Pay attention to the fact that when using var_dump, the quotes are not escaped and thus no slashes exist in the string (the nested quotes are not escaped).
When that array is run through the second function (the encoder), the original JSON string should be returned.
Things I've tried:
I tried setting the $depth of json_decode() to 1. This, however, only throws exceptions when the limit has been reached.
I tried decoding the whole string using json_decode() and then looping over the top-level key-value pairs to run json_encode() over any value that is an array (which should indicate a nested value). The end result was fine at first, but when converting back to a JSON string it escaped the double quotes with slashes. In that case, the end result isn't the same as the original, as the end result includes slashes.
Notes
Even though this question has a very similar title to this one, that one doesn't actually contain answers for its title. There is only an answer on how to transform the invalid JSON string to a valid JSON.
I'd rather not use any RegEx, as that just makes my life more complex than it needs to be ;). But if it can't be avoided, then that's life I guess.
As requested by deceze:
$jsonString = "{ \"foo\": \"bar\", \"nested\": { \"nested_key\": \"nested_value\" }, \"another_top_level_key\": \"some_useful_value\" }";
$decoded = json_decode($jsonString, true);
foreach ($decoded as $key => $value) {
if (is_array($value)) {
$decoded[$key] = json_encode($value);
}
}
$encoded = json_encode($decoded);
var_dump($encoded);
The result is this:
string(102) "{"foo":"bar","nested":"{\"nested_key\":\"nested_value\"}","another_top_level_key":"some_useful_value"}"
Which means that in the end, it did escape the quotes, which is something I cannot accept :(.
Use a function to check when you have an element as array then convert back to json:
<?php
$json = "{
\"foo\": \"bar\",
\"nested\": {
\"nested_key\": \"nested_value\"
},
\"multinested\": {
\"multinested_key\": {
\"multinested_key\": \"nested_value\"
}
},
\"another_top_level_key\": \"some_useful_value\"
}";
$array = json_decode($json, true);
foreach($array as &$item) {
if (is_array($item)) {
$item = json_encode($item);
}
}
print_r($array);
Output:
Array
(
[foo] => bar
[nested] => {"nested_key":"nested_value"}
[multinested] => {"multinested_key":{"multinested_key":"nested_value"}}
[another_top_level_key] => some_useful_value
)
The trick is to use the decode twice:
$array = json_decode(json_decode($json, true), true);
print_r($array);
By POST I get this JSON (can have more than 3 values in it)
{"preferences":["Theater","Opera","Danse"]}
Well, I need to get
array('Theater', 'Opera', 'Degustation')
json_decode doesn't work.
Do you have any ideas please?
Thank you by advance
Try adding the true parameter:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true );
var_dump($arrayData['preferences']);
The last line outputs the following:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
Which is what you want. Good luck!
That JSON string is wrapped in an object (denoted by curly braces {}). json_decode will give you the wrapper object whose "preferences" property is the array you're looking for.
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
json_decode might also be unavailable if you're using and older version of php. In that case you should try a php json library.
You might have used the output of the json_decode() function as an associated array while you hadn't have told the function to provide an associated array for you, or vice versa!! However, the following will get you the array at the preferences index:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ( [0] => Theater [1] => Opera [2] => Danse )
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>
I am facing a strange issue with my PHP code (I'm a beginner to PHP so apologies for my bad coding skills). Each array item in my JSON has a unique ID associated with it, to delete an array I just pass the unique ID to my code and it deletes the array item associated with it, but all my array items contain an integer field and that doesn't get deleted and it messes up my JSON (parsing fails when I try to do so later).
<?php
$var1 = filter_input(INPUT_POST, 'unique_id', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "unique_id" parameter is not set');
}
$data = file_get_contents('feed.json');
if ($data === false) {
die('An error occurred when opening "feed.json"');
}
$json = json_decode($data, true);
if ( ! isset($json[0]['unique_id'])) {
die("The JSON was not decoded correctly");
}
foreach ($json as $key => $value) {
if ($value['unique_id'] == $var1) {
unset($json[$key]);
}
}
$new_json_string = json_encode($json);
file_put_contents('feed.json', $new_json_string, JSON_UNESCAPED_SLASHES | LOCK_EX);
echo "Success";
?>
Here's the sample JSON:
[
{"student_id":"22222222","unique_id":"862916786a1340afbfdf23caa541963f","status":"Hey yo what's up","image":"none","likes":"0"},
{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"none","likes":22}
]
after deleting, I'm left with
{"1":{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"","likes":31}
As you can see {"1": is invalid and shouldn't be there.
Does anyone know what am I doing wrong?
EDIT: Here's my code to create a new array item in my JSON
$json = file_get_contents('feed.json');
$data = json_decode($json);
$data[] = array('student_id' => "$student_id", 'unique_id' => "$unique_id" ,'status' => "$status_txt", 'image' => "$image_link", 'likes' => "0");
file_put_contents('feed.json', json_encode($data), JSON_UNESCAPED_SLASHES | LOCK_EX);
This is a combination of two things:
There is no representation of sparse Arrays in JSON
JSON's arrays with [] can only have a comma-separated list of contiguous elements starting from index 0.
No type information distinguishes JSON arrays and JSON objects in PHP
Both of these things are stored as PHP's array type. JSON objects use the associative keys.
When you unset index 0 from your array, it becomes sparse. Now, the only way to encode something that has a something[1] but no something[0] in JSON is to have an object with a key "1".
PHP's JSON encoder allows this because the array you pass in is of the right type (array) to be serialized as a JSON object. So it does this.
Maybe you wanted to use array_splice to remove the array element instead of unset.
Use array_values() to convert array as notified by Cheery in comments.
I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));
I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.