how to decode json sting including array and object in PHP? - php

I want to decode json string including array and object in PHP. When i decoded with
$array = json_decode($json, true);
print_r($array);
it return NULL. Let me know, the way to decode json in PHP. This is my json string.
{
success: 1,
message: "Successful!",
save_date: "2013-09-11 04:09:26",
test: [
{
test_id: "1",
test_date: "2013-09-12",
test_name: "Test 1"
},
{
test_id: "2",
test_date: "2013-09-11",
test_name: "Test 2"
}
]
}

That's not a valid JSON object. JSON objects must enclose all property names in double quotes:
{ "success": 1, "message": "Successful!" }
PHP provides the handy json_last_error_msg function to tell you that.
There's also the online tool JSONLint to validate JSON strings.

Your JSON is invalid, the property names need to be in quotes too.
Like this:
{
"success": 1,
"message": "Successful!",
"save_date": "2013-09-11 04:09:26",
"test": []
}
Hint: use JSONLint to validate your JSON.

your json string should be like the following :
$sJson = '{"success": 1,"message": "Successful!","save_date": "2013-09-11 04:09:26",
"test": [ {"test_id": "1","test_date": "2013-09-12","test_name": "Test 1"},
{"test_id": "2","test_date": "2013-09-11","test_name": "Test 2"}]}';

Use this
$result=(array)json_decode('your json string');
I think it's working for you

Related

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

PHP Only Returning Last JSON Object

I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason json_decode is only returning the last item in the JSON array. Here's the JSON:
{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}
And the PHP:
<?php
//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);
var_dump($filey);
?>
The result is only the last item in the array:
array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)
Using json_last_error returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.
I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?
That's because your json object names "person" within json array are similar so json decode will override the values with latest.
Consider something like
{
"person1": {
"lname": "smith",
"fname": "bob"
},
"person2": {
"lname": "jones",
"fname": "jane"
}
}
and your code will work fine.
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true) will give me the array shape I expect.
Happy coding.
When you use json_decode(true), your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true), then change "person" to "person1" or so.
Try both var_dump($filey) and var_dump($json), you will see what I'm talking about.

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
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 recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

Parse json array without value in php

I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?
In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE
use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.

json_encode, json_decode, array?

I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}

Categories