unable to read json objects in php - php

I want to read JSON in php:
$productsArr = json_decode(stripslashes($_GET['object'])); //this give me word Array
stripslashes($_GET['object']) //gives me [{"code":"44-3"}]
echo $productsArr->{'code'}; //gives me nothing
I even tried this:
foreach($productsArr as $article)
{
echo $article->code; //nothing is echoing
}
How to access the JSON formatted data in a loop?

1) Force an array to be returned by supplied true to second argument of json_decode.
2) Ensure that this produces an array:
$productsArr = json_decode(stripslashes($_GET['object']), true);
print_r($productsArr);
Assuming it does. Access your elements as such:
echo $productsArr['foo']['bar'];

Related

I can't change JSON into a PHP array

For some strange reason I can't change the following JSON to a PHP array:
{"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},"sides1":{"name_nl":"Achterkant100","name":"Backside100","template_overlay":"1"}}
I've validated the json and it's valid.
First I post $product['sides'] to my page, containing:
"{\"sides0\":{\"name_nl\":\"Voorkant100\",\"name\":\"Frontside100\",\"template_overlay\":\"\"},\"sides1\":{\"name_nl\":\"Achterkant100\",\"name\":\"Backside100\",\"template_overlay\":\"1\"}}"
Then I use json_decode on it like this:
$sidearr = json_decode($product['sides'], true);
If I then do:
echo '<pre>';
print_r($sidearr);
echo '</pre>';
It prints the first part of my question.
Now I want to loop over it, but even this test shows nothing:
foreach($sidearr as $side){
echo 'test';
}
I tried testing if it even is an array with:
echo is_array($sidearr) ? 'Array' : 'not an Array';
echo "\n";
And it shows me that it is not an array. Why is that? I always thought using json_decode on a json string and add true inside the function turns it into a PHP array.
It prints the first part of my question.
Because $sidearr is a string now, decode it again, you'll get an array.
$sidearr = json_decode($sidearr, true);

Cannot loop through items in JSON (php) [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i have the following Json sent via ajax to test.php:
[{},{"product[]":"john","qty[]":"12","price[]":"100","total[]":"1200"},{"product[]":"juan","qty[]":"22","price[]":"3.5","total[]":"77"},{"product[]":"louis","qty[]":"99","price[]":"1.22","total[]":"120.78"},{"product[]":"paul","qty[]":"5","price[]":"2.1","total[]":"10.5"},{"product[]":"carl","qty[]":"9","price[]":"14","total[]":"126"},{"total_amount":"1533.00"}]
In my php file I am trying to loop through each individual product[], qty[], price[] and list values:
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
// echo json_encode($obj[1]->{'product[]'}); //(works)
foreach($obj as $item) {
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
?>
but this throws an error.
What is wrong in my loop?
There are a couple of things wrong with the code, the first is that you decode as objects and try and use this as an array. You need to pass true as the second parameter to json_decode() to make it an associative array.
The second is that your array contains elements which don't have all of the details. The last element only has "total_amount", so none of the other fields exist. This is why I use
if ( isset($item['product[]'])){
to check the object before outputting the data...
$obj = json_decode($_POST["mydata"], true);
header('Content-Type: application/json');
foreach($obj as $item) {
if ( isset($item['product[]'])){
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
}
Pass true as second argument to json_decode.
Per the documentation:
assoc
When TRUE, returned objects will be converted into associative arrays.
So your code becomes:
$obj = json_decode($_POST["mydata"], true);
Also note that the first entry in your array is empty, so you're gonna have to check for that.

parsing a json array does not give me the values

below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories