Parsing through json string php - php

im new with JSON and have had massive struggle trying to parse this JSON
{
"730": {
"success": true,
"data": {
"price_overview": {
"currency": "USD",
"initial": 1499,
"final": 1499,
"discount_percent": 0
}
}
}
}
I have tried different approaches but still struggle to get the value of initial in price_overview

You need to json_decode, and then, just use the dictionary that is generated to grab the value. Like this:
$json = <<< JSON
{
"730": {
"success": true,
"data": {
"price_overview": {
"currency": "USD",
"initial": 1499,
"final": 1499,
"discount_percent": 0
}
}
}
}
JSON;
$json_a = json_decode($json, true);
echo $json_a['730']['data']['price_overview']['initial'];
CodePad
http://codepad.org/i1ELBxd9
Further Reading
Using JSON with PHP

Try this:
<?php
$data = '{"730":{"success":true,"data":{"price_overview":{"currency":"USD","initial":1499,"final":1499,"discount_percent":0}}}}';
$json = json_decode(trim($data), true);
echo '<pre>';
print_r($json[730][data][price_overview]);
echo '</pre>';

Related

var_dump and print_r displays different results - PHP

I have a string (JSON type), i wanted to convert it to PHP Array.
{
"action":"putEntity",
"dataPacket":{
"entity":[
{
"name":"product",
"data":[
{ }
]
}
]
}
}
I did following to do so,
$array = json_decode(json_encode($data), True);
When i do var_dump($array); it displays:
string(1578) "{ "action": "putEntity", "dataPacket": { "entity": [{ "name": "product", "data": [{ }] }] } }"
But when i do, print_r($array); it displays:
{
"action": "putEntity",
"dataPacket":{
"entity":[
{
"name": "product",
"data":[{}]
}
]
}
}
Issue is when i try to print $array['dataPacket']; it throws error illegal string offset 'dataPacket'
why var_dump is showing it as String? please help.
$array = json_decode(json_encode($data), True);
Should be
$array = json_decode($data, true);

PHP Json Parsing 6

How do I pull the 76561198216468627 from
{ "response": { "steamid": "76561198216468627", "success": 1 } }
I've tried this but it pulls 1 instead of the id
foreach ($parsed_json->{'reponse'} as $item) {
$steamid = $item;
}
You need to decode the JSON string into either a PHP object or array. Here's how to do it each way:
ARRAY METHOD
$jsonString = '{ "response": { "steamid": "76561198216468627", "success": 1 } }';
$json = json_decode($jsonString, true);
foreach($json as $item)
{
$steamid = $item['steamid'];
}
OBJECT METHOD
$jsonString = '{ "response": { "steamid": "76561198216468627", "success": 1 } }';
$json = json_decode($jsonString);
foreach($json as $item)
{
$steamid = $item->steamid;
}
Try this:
$json = '{
"response": [{ "steamid": "76561198216468627", "success": 1 }]
}';
$decode = json_decode($json);
echo $decode->response[0]->steamid;
Then you can get 76561198216468627

Extract each level data with php

The following is the JSon data.
{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}
I need to parse
- entity
- quizAnswerChoices (count the item)
How to retrieve each choiceText etc
Use
$json='{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}';
$encodedJson= json_decode($json,true);
$quizAnswerChoices=$encodedJson['entity'][0]['quizAnswerChoices'];
echo 'Count: '.count($quizAnswerChoices);
Use this
$arry = json_decode($json,true);
foreach ($arry['entity'] as $ke => $ve) {
foreach ($ve['quizAnswerChoices'] as $k => $v) {
print_r($v);
}
}
Lets consider you are recieving this json in a variable called "$contents".
All you have to do is decode it:
$decoded = json_decode($contents, true); //True so, the decoded object will be converted into an ssociative array
print_r($decoded);
If you do a json_decode like
$data = json_decode(json_data);
Then $data will be a traversable array
$data['entity']['quizAnswerChoices'] etc
Use json_decode to convert json to array
$dataArray = json_decode($json_string, true)
$dataArray['entity']; // entity
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
count($dataArray['entity']['quizAnswerChoices']); // quizAnswerChoices count

How to Parse JSON with PHP?

I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.
{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}
I used the following so far to try and parse it.
$json_file = file_get_contents('test.json');
$json_a = json_decode($json_file,true);
var_dump(json_decode($json_file)); //This works
echo $json_a['name']; //I want to print the name of each (from timers).
Try:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:
echo json_last_error_msg()
To troubleshoot further
You need do it in following manner:-
<?php
$data = '{
"metrics": {
"timers": [
{
"name": "com.android.timer.launchtime",
"startTime": 1232138988989,
"duration_ms": 1900
},
{
"name": "com.android.timer.preroll-load-time",
"startTime": 1232138988989,
"duration_ms": 1000
}
]
}
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
echo $new_arr->name.'<br/>'; // rest you can do also same
}
?>
Output:- https://eval.in/407418

handling nested json in looping

json after json_encoded
{
"data":[
{
"name":"JIN",
"id":"100007934492797"
},
{
"name":"aris",
"id":"100008128873664"
},
{
"name":"Madm",
"id":"34234234"
}
],
"paging":{
"next":"https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
I want to store the name and ID of my json in db. But when I use for loop there's a problem with the offset, I suspect it's the last part of the json. How to remove the paging part? I tried
foreach($friends as friend){
echo friend[0]->name;
}
First, your original code would never work:
foreach($friends as friend){
echo friend[0]->name;
}
Those references to friend should have $ in front of them making them $friend. Then to solve your larger issue, just use a nested foreach loop:
$json = <<<EOT
{
"data": [
{
"name": "JIN",
"id": "100007934492797"
},
{
"name": "aris",
"id": "100008128873664"
},
{
"name": "Madm",
"id": "34234234"
}
],
"paging": {
"next": "https://graph.facebook.com/v1.0/1380314981/friends?limit=5000&offset=5000&__after_id=enc_AeyRMdHJrW0kW9vIZ41uFPXMPgE-VwRaHtQJz2JWyVc0hMl9eOG10C6JWjoCO8O2E4m24EPr28gIt9mxQR8oIQmN"
}
}
EOT;
$friends = json_decode($json);
foreach($friends as $friend_data){
foreach($friend_data as $friend){
echo $friend->name . '<br />';
}
}
And the output of this would be:
JIN
aris
Madm
Additionally, if working with arrays makes more sense for you, you can always set json_decode to return an array by setting the second parameter to true. Here is refactored code as an example:
$friends = json_decode($json, true);
foreach($friends as $friend_data){
foreach($friend_data as $friend_key => $friend_value){
if (isset($friend_value['name'])) {
echo $friend_value['name'] . '<br />';
}
}
}

Categories