Php - json_decode returns null [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to decode json string that looks like the one below with json_decode php function:
"{id:"1",fields:[{id:"1",value:"asdasd"},{id: "2",value:"asdasd"},{id:"3",value:"asdasd"}]}"
I have tried various options from this question. Like:
$foo = utf8_encode($json_string);
$data = json_decode($foo, true);
Or:
json_decode(str_replace ('\"','"', $json_string), true);
Even with:
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
But, everything I try I always get null.
Why is that?

First of all, your JSON is invalid. You should always first validate your JSON before asking with any JSON lint tool, which would tell you exactly where and what the error is.
Also, you should always check for errors when handling JSON in PHP. You can check out the json_last_error function's official documentation on how to properly perform the validation.
$json = 'your_json_string';
$array = json_decode($json, true);
if (json_last_error()) {
die('Invalid JSON provided!');
}
printf('<pre>Valid JSON output: %s</pre>', print_r($array, true));
Worth mentioning: since PHP 7.3 a JSON_THROW_ON_ERROR option was added so the code can be wrapped around with a try-catch block:
try {
$array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
printf('Valid JSON output: %s', print_r($array, true));
} catch (\JsonException $exception) {
printf('Invalid JSON input: %s', print_r($exception, true));
}
Working example.

<?php
$data='{
"id": "1",
"fields": [{
"id": "1",
"value": "asdasd"
}, {
"id": "2",
"value": "asdasd"
}, {
"id": "3",
"value": "asdasd"
}]
}';
$dataNew=json_decode($data,true);
echo '<pre>';
print_r($dataNew);
Your json was not valid. The json-keys need to be inside double-quotes. After that json_decode will work fine.
Output is:
Array
(
[id] => 1
[fields] => Array
(
[0] => Array
(
[id] => 1
[value] => asdasd
)
[1] => Array
(
[id] => 2
[value] => asdasd
)
[2] => Array
(
[id] => 3
[value] => asdasd
)
)
)

Your JSON returns Null because in JSON, the keys should be string.Your JSON format is incorrect and hence returns Null.
Try rewriting it as:
{
"id":"1",
"fields":[
{
"id":"1",
"value":"asdasd"
},
{
"id": "2",
"value":"asdasd"
},{
"id":"3",
"value":"asdasd"
}
]
}

Related

Python to PHP | String to Multidimensional Json Object To Array

I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)

How to convert JSON string to PHP object or array creation *code* [duplicate]

This question already has answers here:
print an array as code
(4 answers)
Closed 4 years ago.
FIRSTLY: This is a totally different question - How to convert JSON string to array
MY QUESTION...
I have a valid JSON string assigned to a php variable, $json.
I know that I can run it into json_decode($json, true); to parse into a php array at runtime, however I want to go a step beyond and convert this into a reusable php array code string, which can be simply copied and pasted into a php script, like $array = 'php array code here'.
For those who will inevitably ask "why?", an example:
to copy an example JSON endpoint parameter from an API's docs, then quickly convert to php array string code to paste into a test script as a valid test parameter for making a POST request
I know that I can do this:
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '<pre>';
echo '$phpArray = ' . print_r(json_decode($json));
echo '</pre>';
exit;
Which gets you close...
$phpArray = Array
(
[0] => stdClass Object
(
[ID] => 1
[Name] => Test One
)
[1] => stdClass Object
(
[ID] => 2
[Name] => Test Two
)
)
But there is of course still some work to do... currently I would copy this into Sublime Text or some other similar text manipulation tool and just use find/replace or regex find/replace in some cases. But what I am looking for is a quicker, more elegant solution whereby I could literally copy+paste that JSON into some script (or anywhere!), and run it to get this:
$phpArray = [
0 => [
'ID' => 1,
'Name' => 'Test One',
],
1 => [
'ID' => 2,
'Name' => 'Test Two',
],
];
Has someone created a good tool to do this already somewhere? I couldn't find anything. I am open to ANY elegant solution and will happily upvote any answer that is an improvement on this rudimentary means of bridging from the JSON to a PHP object / array creation code. Thanks!
<?php
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '$output = '.var_export(json_decode($json, true), true).';';
Output:
$output = array (
0 =>
array (
'ID' => '1',
'Name' => 'Test One',
),
1 =>
array (
'ID' => '2',
'Name' => 'Test Two',
),
);

JSON & Array get data with PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a question about some JSON and PHP, see json below.
How can I get the number string?
{
”data”: [
{
”numbers”: [
{
”number”: "XXXX",
”type”: ””
}
]
}
]
}
Ive tried with the following but its not working:
$item['numbers'][0]->number;
Note, the $item array is ok. I just do not know what is wrong here.
EDIT:
I should point out that there was an json_decode before.
So the structure looks like this:
Array
(
[0] => Array
(
[number] => XXXX
[type] =>
)
)
print_r($item['numbers']);
This doesn't work: $item['numbers'][0]['number'];
Error: Undefined offset: 0 in
Thanks!
if you want to direct access then use this code
$items->data->numbers->number;
you can use php json_decode().it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '{
"data": [
{
"numbers": [
{
"number": "11",
"Type": ""
}
]
}
]
}';
$array=json_decode($json_data,true);
echo "<pre>";
print_r($array);
echo $array["data"][0]["numbers"][0]["number"];
then output
Array
(
[data] => Array
(
[0] => Array
(
[numbers] => Array
(
[0] => Array
(
[number] => 11
[Type] =>
)
)
)
)
)
Number:11
To get the number try this :
$myJSON->data->numbers->number;
Hope this will help you out... You are trying to access which does not actually exists.
try this code snippet here
<?php
ini_set('display_errors', 1);
$month_options = '{
"data": [
{
"numbers": [
{
"number": "10",
"Type": ""
}
]
}
]
}';
$array=json_decode($month_options,true);
echo $array["data"][0]["numbers"][0]["number"];
Use the json_decode() function of PHP.
$array = json_decode('{
”data”: [
{
”numbers”: [
{
”number”: "",
”Type”: ””
}
]
}
]
}', true);
Then you could access it as $array["data"]["numbers"]["number"];

Searching JSON PHP

I have JSON that looks like this (shortened for readability):
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.
$heroid = $myplayer['hero_id'];
$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);
foreach ($heroesarray as $parsed_key => $parsed_value) {
if ($parsed_value['id'] == $heroid) {
$heroname = $parsed_value['localized_name'];
}
}
Easy. Just use json_decode(). Explanation follows the code at the bottom.
// First set the ID you want to look for.
$the_id_you_want = 2;
// Next set the $json.
$json = <<<EOT
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
EOT;
// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);
// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
echo '<pre>';
print_r($decoded);
echo '</pre>';
}
// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
// Since this json is an array in another array, we need anothe foreach loop.
foreach ($decoded_array_value as $decoded_key => $decoded_value) {
// Do a comparison between the `$decoded_value['id']` and $the_id_you_want
if ($decoded_value['id'] == $the_id_you_want) {
echo $decoded_value['localized_name'];
}
}
}
Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:
Array
(
[heroes] => Array
(
[0] => Array
(
[name] => antimage
[id] => 1
[localized_name] => Anti-Mage
)
[1] => Array
(
[name] => axe
[id] => 2
[localized_name] => Axe
)
[2] => Array
(
[name] => bane
[id] => 3
[localized_name] => Bane
)
)
)
First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].
But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.
json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.
$json = ''; // JSON string
$data = json_decode($json, true);
foreach($data['heroes'] as $hero) {
if($hero['id'] === 2) {
var_dump($hero['localized_name']);
// Axe
// This will stop the loop, if you want to keep going remove this line
break;
}
}

Issue with JSON and jQuery Iteration

I'm pretty sure it's an obvious error somewhere on this - but let me explain what I'm donig :
I'm calling a PHP file via jQuery as follows :
$.getJSON("/phpincs/getbucket.php?awskey="+awskey+"&awssecret="+awssecret+"&bucket="+bucket,
function(json){
$.each(json,function(i,item){
$(new Option(item.name,item.name)).appendTo('#bucket_contents_0');
});
}
and the JSON file it returns is as follows :
Array
(
[bt_shop.png] => Array
(
[name] => bt_shop.png
[time] => 1260393948
[size] => 156985
[hash] => 8a4eba621d5e08b84c962a0ad21ec2ae
)
[me_profile.jpg] => Array
(
[name] => me_profile.jpg
[time] => 1260393952
[size] => 2714
[hash] => 4f5d185b0c671e6165902762681f098b
)
[thumbnail.aspx.jpeg] => Array
(
[name] => thumbnail.aspx.jpeg
[time] => 1260393951
[size] => 5268
[hash] => 6939efa58ff7ffcac17218ffdd0d5d8c
)
)
true
for some reason it doesn't seem to fire the function(json){} - I've stuck an alert(''); in and it doesn't do anything.
Can someone quickly explain to me what seems to be going wrong there?
Cheers,
Carl
It is more than likely not calling the callback function because it doesn't look like what you are returning is json. If you have an $variable defined that contains your array...call
echo json_encode($jsondata); exit;
At the end of your script.
I've changed the names of the inner arrays as your previous labels are going to cause problems with the dot. You will get an error like:
myArray.bt_shop is undefined
when you try to call
alert(myArray.bt_shop.png.name);
the only way it could be called is with
alert(myArray["bt_shop.png"].name);
So having changed your code a bit, this is the JSON version of your arrays...
{
"one":
{
"name": "bt_shop.png",
"time": "1260393948",
"size": "156985",
"hash": "8a4eba621d5e08b84c962a0ad21ec2ae"
},
"two":
{
"name": "me_profile.jpg",
"time": "1260393952",
"size": "2714",
"hash": "4f5d185b0c671e6165902762681f098b"
},
"three":
{
"name": "thumbnail.aspx.jpeg",
"time": "1260393951",
"size": "5268",
"hash": "6939efa58ff7ffcac17218ffdd0d5d8c"
}
}
Then you reference your fields like this when you have the object:
myArray["two"]["name"]
myArray["two"].name
myArray.two.name
Your returned file isn't JSON. Unless you're using PHP syntax to describe your JSON object for us, you need to encode it into JSON format using json_encode.
What you call the JSON file isn't JSON. Or maybe do you use some PHP library that converts that strange format into JSON ?

Categories