json response handling issue - php

I'm stuck with retrieving json response below is the json output. Your help would be highly appreciated.
{ "productHeader" : { "totalHits" : 684 }, "products" : [ { "name" : "Victoria Hotels", "productImage" : { "url" : "http://hotels.com/hotels/9000000/8640000/8633700/8633672/8633672_20_b.jpg" }, "language" : "en", "description" : "Location. Victoria Hotels is in Foshan (Nanhai) and area attractions include Renshou Temple and New Plaza Stadium. Additional regional attractions include Guangdong Folk Art Museum and Bright Filial Piety Temple.", "identifiers" : { }, "fields" : [ { "name" : "regions2", "value" : "Guangdong" },
Please help me to fetch the particular values. For example if I need to fetch the name, image url from the json response.

You can use json_decode to parse a JSON string to an array and access it's values:
// assuming, that $string contains the json response
// second parameter to true, to get an array instead of an object
$data = json_decode( $string, true );
if ( $data ) {
echo $data['products'][0]['name'];
// or whatever value
} else {
echo 'JSON could not be parsed, error: ' . json_last_error();
}
To show all values in the products array, simple loop it:
if ( $data ) {
foreach($data['products'] as $product){
echo $product['name'];
}
// or whatever value
} else {...

If you're going to use PHP to get the values, check this:
$decodedJson = json_decode($json, true);
print_r($decodedJson);
You will get an array, to get image source and other tags you need to do it in a loop or select concrete index like:
echo $decodedJson['productHeader']['products'][0]['productImage']['url'];
In JS you should extract the values the same way.

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

How to change value of special key in json using php?

I'm inserting value with implode and get this type json
[
{
"id":"1",
"f_name":"Mitrajit",
"l_name":"Samanta",
"class":"XII",
"section":"A,B,C",
"roll":"1",
"status":"1"
}
]
but I want this type :-
[
{
"f_name" : "Mitrajit",
"l_name" : "Samanta",
"class" : "XII",
"section": ["A","B","C"],
"roll" : "1",
"status" : "1"
}
]
how can I get "A,B,C" to ["A","B","C"]?
You need to use json_decode() to converting json to php array. Then select section value in json array and use explode() to converting it to array. At the end convert php array to json using json_encode()
$json = json_decode($jsonStr, true);
$json[0]["section"] = explode(",", $json[0]["section"]);
$jsonStr = json_encode($json);
Check result in demo

PHP - Extracting an array (object?) from a JSON file

I've got a JSON file and I want to access the contents via PHP. The problem is accessing an array inside the JSON file. Other methods suggested on this site don't seem to work. An example of the JSON structure is at the bottom. The PHP code here is the only PHP code between my opening and closing PHP tags.
This PHP code works. I'm accessing something that isn't an array.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['name'];
echo $id;
This doesn't work. I'm trying to access the "name" portion of the "cards" array (object?) in the JSON file.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['cards']['name'];
echo $id;
This also doesn't work:
$id = $data['cards']['name'][0];
The structure of the JSON file with example info:
"name" : "Nemesis",
"code" : "NMS",
"gathererCode" : "NE",
"oldCode" : "NEM",
"magicCardsInfoCode" : "ne",
"releaseDate" : "2000-02-14",
"border" : "black",
"type" : "expansion",
"block" : "Masques",
"onlineOnly" : false,
"booster" : [ "rare", ... ],
"cards" : [ {}, {}, {}, ... ]
The structure of the "cards" array (object?) of the JSON file with example info:
"name" : "Sen Triplets",
"manaCost" : "{2}{W}{U}{B}",
"cmc" : 5,
"colors" : ["White", "Blue", "Black"],
"type" : "Legendary Artifact Creature — Human Wizard",
"supertypes" : ["Legendary"],
"types" : ["Artifact", "Creature"],
"subtypes" : ["Human", "Wizard"],
"rarity" : "Mythic Rare",
"text" : "At the beginning of your upkeep, choose target opponent.
This turn, that player can't cast spells or activate
abilities and plays with his or her hand revealed.
You may play cards from that player's hand this turn.",
"flavor" : "They are the masters of your mind.",
"artist" : "Greg Staples",
"number" : "109",
"power" : "3",
"toughness" : "3",
"layout" : "normal",
"multiverseid" : 180607,
"imageName" : "sen triplets",
"id" : "3129aee7f26a4282ce131db7d417b1bc3338c4d4"
I got the JSON file from here: http://mtgjson.com/ . The file references the card game Magic: the Gathering. I'm using PHP because my intention is to eventually load the data into a MySQL database.
It looks like cards key holds an array of json objects. json_decode() will parse it as such.
Given that, $data['cards'][0]['name'] should give you the name of first card. Analogically, $data['cards'][1]['name'] should give you name of the second card.
The $data['name'] you were targeting was the one from the extension.
You need to access the array ['cards'] to reach the card list then with a loop you can get all the cards name.
you might want to do that :
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = json_decode($jsondata, true);
$cards = $data['cards'];
$cardsName = array();
foreach ($cards as $card) {
$cardsName[] = $card['name'];
}
var_dump($cardsName);
This will create an array will all the cards name
You need to unserialize your data
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = unserialize($jsondata);
// Show the unserialized data;
var_dump ($data);

How to access JSON object without knowing its name (and that is not in an array)

My problem is rather simple, at least I hope so, but I just cannot find the solution. I have a JSON string, which I got from a get request to a server.
Exemple of my JSON :
"body":[
{
"_id":"70:ee:50:05:00:aa",
"place":{
"location":[
2.4358958,
49.503012
],
"altitude":89,
"timezone":"Europe/Paris"
},
"mark":8,
"measures":{
"02:00:00:04:f8:6a":{
"res":{
"1431926951":[
7.9,
83
]
},
"type":[
"temperature",
"humidity"
]
},
"70:ee:50:05:00:aa":{
"res":{
"1431932787":[
1009.4
]
},
"type":[
"pressure"
]
}
},
"modules":[
"02:00:00:04:f8:6a"
]
},
I need to accessthe temperature value, so following this example I would do this : $value = body->measures->02:00:00:04:f8:6a->res->1431926951[0].
I know i can't just do this : measures->02:00:00:04:f8:6a. The cool thing is that this difficulty can be solved doing this : $module = body->modules[0] and then I can use this variable.
So it would look like this : body->measures->$module->res->1431926951[0].
What I can't seem to do though is the final step : res->1431926951[0]. This number seem completely random I can't find this value anywhere else in the JSON so I can't use the same trick I did for 02:00:00:04:f8:6a.
So my question is how can I access the first value of the array located inside the object "1431926951" without knowing its name ?
Thank you very much for taking the time to help me.
EDIT : here is the code I am using in PHP
$results = json_decode($resp);
foreach($results->body as $result){
$id = $result->_id;
$lat = $result->place->location[0];
$lng = $result->place->location[1];
$module = $result->modules[0];
$type = $result->measures->$module->type[0];
$value = "1431926951";
//$test = $result->measures->$module->res->$value[0];
/*$res = $result->measures[$result->measures[0]]->res;
$test = $res[Object.keys($res)[0]][0];*/
echo 'Id: '.$id.' - Lat: '.$lat.' - Lng: '.$lng.' - test: '.$test."<br>";
}
You can access with the Object.keys to the name of the property in JavaScript.
var res = obj.body.measures[ obj.body.modules[0] ].res;
console.log( res[ Object.keys(res)[0] ][0]); // prints 7.9
See demo
EDIT (PHP version, only 2 lines):
With PHP is the same but using key and stdClass (json_decode returns stdClass)
$res = $obj->body->measures->{ $obj->body->modules[0] }->res;
echo $res->{ key( (array) $res ) }[0]; // prints 7.9
See demo
Hope help.
Here's how I did it in PHP:
<?php
$ob = '
{
"body":[
{
"_id":"70:ee:50:05:00:aa",
"place":{
"location":[
2.4358958,
49.503012
],
"altitude":89,
"timezone":"Europe/Paris"
},
"mark":8,
"measures":{
"02:00:00:04:f8:6a":{
"res":{
"1431926951":[
7.9,
83
]
},
"type":[
"temperature",
"humidity"
]
},
"70:ee:50:05:00:aa":{
"res":{
"1431932787":[
1009.4
]
},
"type":[
"pressure"
]
}
},
"modules":[
"02:00:00:04:f8:6a"
]
}
]
}';
//turn the json into a PHP object
$ob = json_decode($ob);
//pre-defined array of known module names
$modules = array("02:00:00:04:f8:6a", "70:ee:50:05:00:aa");
//loop through each moduke
foreach($modules as $module){
//get the 'res' property for that module
$res = $ob->body[0]->measures->$module->res;
//get a list of the object properties
$properties = get_object_vars($res);
//select the first property (we don't know the name) uising the current() function
$firstProperty = current($properties);
//and print it out
echo "The first property of $module is: ";
print_r($firstProperty);
echo "<br/><br/>";
}
var jsonvar = { key: { key1: "value 1", key2: "value 2" } };
var key = Object.keys(jsonvar)[0];
This is how we can get the json key from the given json object using javascript.
Explaination: Lets say you have a json variable in javascript named jsonvar which is holding some json data. Now, to access the first key contained in parent json, then make use of array as shown above.
Object.keys(jsonvar)[0]
will return the json key: "key". We are accessing the jsonvar to access the first key which corresponds to position [0].
Hope this could solve your problem.

PHP JSON not decoding properly

I'm trying top decode this JSON data with PHP, but it's not returning anything:
{ "message" : "",
"result" : [ { "Ask" : 0.040400209999999999,
"BaseVolume" : 456.53976963999997,
"Bid" : 0.040200010000000001,
"Created" : "2014-12-19T03:48:49.13",
"High" : 0.044610999999999998,
"Last" : 0.040400199999999997,
"Low" : 0.037999999999999999,
"MarketName" : "BTC-XPY",
"OpenBuyOrders" : 194,
"OpenSellOrders" : 520,
"PrevDay" : 0.042073039999999999,
"TimeStamp" : "2014-12-30T02:45:32.983",
"Volume" : 11072.491576779999
} ],
"success" : true
}
This is what I have so far:
$pricejson = file_get_contents('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-xpy');
$price = json_decode($pricejson, true);
echo $price->result->Last;
When I open the php file containing this code, there's nothing. If I use echo $pricejson, I get the whole thing printed out so I definitely have the data.
What is wrong?
The second argument to json_decode forces all objects to be parsed as associative arrays so you need to access it with array notation. Additionally result is an array always so you need to loop over it or access it by index:
$price = json_decode($pricejson, true);
// print the first price
echo $price['result'][0]['Last'];
// print all prices:
foreach ($price['result'] as $data) {
echo $data['Last'];
}
Or if you want a mix of objects/arrays then:
$price = json_decode($pricejson);
echo $price->result[0]->Last;
// print all prices:
foreach ($price->result as $data) {
echo $data->Last;
}
In top of this its possible there is a json parse error. You might also need to make sure that the JSON you get back is being parsed properly.

Categories