PHP JSON Data Selection - php

How would I go about selecting the data of each title from the following JSON?
I have the JSON decoded, but I'm not sure how to select the part I want.
{
"responseData": {
"results": [
{
"title": "Justin Giesbrecht 749",
"titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
I thought it would be something like this, but I don't get anything:
echo "Response ". $jsonS->responseData->results[1]->title;

Actually you've got the reading of the title part right, it's the JSON that is invalid.
Copying the JSON into a JSON validator/lint e.g. http://www.jsonlint.com/ will show that the you have additional , (commas) after the last object attribute in a few places (5 places to be exact, after each 'titleFormatting' attribute and after 'currentPageIndex').
If you fix those errors and parse it using json_decode e.g.:
$jsonS = json_decode($json_text);
Then your own code:
echo "Response " . $jsonS->responseData->results[1]->title;
Will output the second (index 1 being the second index) results title
Response Gopher dunes 09

When you json_decode something it is converted to a regular PHP array, so you can reference it like $decodedObject["nodeName"].

When I parse that JSON as you quoted it with PHP's json_decode method, it gives me NULL because PHP doesn't think it's valid JSON. Add a var_dump($jsonS); to see if this is happening to you as well. If it is, you may need to be sure your JSON is valid.
Here's what I did, for reference:
$json_data = <<<END_OF_JSON
{
"responseData": { "results": [
{
"title": "Justin Giesbrecht 749", "titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [ {
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
END_OF_JSON;
$jsonS = json_decode($json_data);
var_dump($jsonS);
echo "Response ". $jsonS->responseData->results[1]->title;
And the output was:
NULL Response
If you're using different JSON, please edit your question and share it. But if you're actually using the above, it's not valid...

In JSON you are not allowed to leave trailing comma in array/object definition. So, when in PHP is perfectly valid to write:
$a = array(1,2,3,);
(note last comma), in JSON
a : [1,2,3,]
or
a : {x :'y',}
is invalid.

Related

PHP: search and remove JSON object

I have a quite nested JSON file. How can I delete an array that includes my value? For ex: I want to delete {"customer":"Customer1","date":"2017-06-03"...} from JSON file and I already knew the "Customer1"
{
"info": [{
"customer": "Customer1",
"date": "2017-06-03",
"beacons": [{
"data1": "1234",
"data2": "Test1",
}, {
"data1": "0088",
"data2": "Test2",
}]
},{
"customer": "Customer2",
"date": "2017-06-03",
"beacons": [{
"data1": "dcdd4",
"data2": "Test3",
}, {
"data1": "0088",
"data2": "Test4",
}]
}]
}
Thanks!
There is some issue in your json data. This is not valid json data; I have decoded the josn data & then check if "customer" value = 'Customer1', then remove the array from main array.
It should be like this:
$jsonData = '{"info ": [{
"customer ": "customer1 ",
"date ": "2017 - 06 - 03 ",
"beacons ": [{
"data1 ": "1234",
"data2 ": "Test1"
}]
}, {
"customer": "customer2 ",
"date": "2017 - 06 - 04 ",
"beacons": [{
"data1": "dcdd4",
"data2": "Test3"
}]
}]
}';
$myData = json_decode($jsonData,true);
foreach($myData["info"] as $k=>$arr) {
if($arr["customer"] == "customer1") {
unset($myData["info"][$k]);
}
}
one small correction in the previous answer .
please call function like this . the searching value should be a value like astring format .
searchObj (myobj, 'Customer1');
make the object to assign to one obj example :=>
var myobj={"info": [{ ...... }]}
.this below function will work for the searching the exact value in object array
call the function with the parameters as like below
searchObj (myobj, Customer1);
function searchObj (obj_name, searchingval) {
for (var key in obj_name) {
var value = obj_name[key];
if (typeof value === 'object') {
searchObj(value, searchingval);
}
if (value === searchingval) {
console.log('property name=' + key + ' property value=' + value);
}
}
}

Retrieving JSON from site equals NULL

$url="https://alcurex.com/api/market.php?pair=mrc_ltc&price=buy";
$json = file_get_contents($url);
$data = json_decode($json);
echo $json;
var_dump($data);
Results in a null response. However when you visit the page you get a html read out of
{
"pair": MRC_LTC,
"time": "2014-07-23 07:34:54,
"price": 0.00000017,
"volume": 558.99741176,
"type": Buy
},
Response is not valid JSON format.
{ "pair": MRC_LTC, "time": "2014-07-23 07:34:54, "price": 0.00000017, "volume": 558.99741176, "type": Buy },
You could check it from Firefox console, correct JSON should be this:
var s = {
"pair": "MRC_LTC",
"time": "2014-07-23 07:34:54",
"price": 0.00000017,
"volume": 558.99741176,
"type": "Buy"
};
Errors:
Missing " for pair, time and type
Unnecessary comma at the end of string
You have three problems with this JSON:
pair value is not a valid type, if it should be string, it's missing quotes
time has string start quote but does not end it
type value is not a valid type, if it should be string, it's missing quotes
This is a valid JSON:
{
"pair": "MRC_LTC",
"time": "2014-07-23 07:34:54",
"price": 0.00000017,
"volume": 558.99741176,
"type": "Buy"
}

How to read JSON results from PHP

How to access element of below json output using php ..
{
"ISBN:9781430215752": {
"bib_key": "ISBN:9781430215752",
"preview":
"restricted",
"preview_url":
"https://archive.org/details/linuxrecipesforo00kuhn",
"info_url": "https://openlibrary.org/books/OL23936576M/Linux_recipes_for_Oracle_DBAs",
"details": {
"lc_classifications": ["QA76.9.D3 K84 2009"],
"latest_revision": 2,
"ocaid": "linuxrecipesforo00kuhn",
"contributions": ["Kim, Charles.", "Lopuz, Bernard."],
"source_records": ["marc:marc_loc_updates/v37.i44.records.utf8:10470755:1047"],
"title":
"Linux recipes for Oracle DBAs",
"languages": [{
"key": "/languages/eng"
}],
"subjects": ["Linux", "Oracle (Computer file)", "Relational databases", "Database management"],
"publish_country": "cau",
"by_statement": "Darl Kuhn, Charles Kim, Bernard Lopuz.",
"type": {
"key": "/type/edition"
},
"revision": 2,
"other_titles": ["Linux recipes for Oracle DataBase Administrators"],
"publishers": ["Apress", "Distributed to the book trade by Springer-Verlag"],
"last_modified": {
"type": "/type/datetime",
"value": "2014-04-06T06:55:36.956977"
},
"key": "/books/OL23936576M",
"authors": [{
"name": "Darl Kuhn",
"key": "/authors/OL1484587A"
}],
"publish_places": ["Berkeley, CA", "New York"],
"oclc_number": ["243543902"],
"pagination": "xxv, 501 p. :",
"created": {
"type": "/type/datetime",
"value": "2009-11-24T23:42:39.524606"
},
"dewey_decimal_class": ["005.75/65 22", "005.26/8"],
"notes": {
"type": "/type/text",
"value": "Includes index."
},
"number_of_pages": 501,
"isbn_13": ["9781430215752"],
"lccn": ["2009277832"],
"isbn_10": ["1430215755"],
"publish_date": "2008"
}
}
}
I tried using below code,
it doesn't work.
$json = json_decode($body);
echo $json->ISBN:9780980200447->info_url;
It's giving an error..
Is there any other easy way to read all elements?
You are on the right track. : is just an invalid character for a property and must be handled special.
echo $json->{'ISBN:9781430215752'}->info_url;
will get you the expected result.
You may also decode as an associative array
$json = json_decode($body, true);
echo $json['ISBN:9781430215752']['info_url'];
I would probably stick to this approach rather than the object oriented, since encapsulating keys makes code less readable
You must use
echo $json->{'ISBN:9780980200447'}->info_url;
since 'ISBN:9780980200447' is your class name.
Reference: php.net
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
Use braces like this:
echo $json->{'ISBN:9781430215752'}->info_url;

Decode json in php and create variables

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.
You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

Looping over nested arrays below keys

Ok, so that title might be a little misleading, but I'm not quite sure what i'm describing, so here goes.
I have the following JSON :
{
"lastModified": 1368517749000,
"name": "Requiem Paradisum",
"realm": "Chamber of Aspects",
"battlegroup": "Misery",
"level": 25,
"side": 1,
"achievementPoints": 1710,
"emblem": {
"icon": 126,
"iconColor": "ffdfa55a",
"border": 3,
"borderColor": "ff0f1415",
"backgroundColor": "ff232323"
},
"news": [
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368482100000,
"itemId": 91781
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368477900000,
"itemId": 87209
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368475800000,
"itemId": 86880
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91781
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91779
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475320000,
"itemId": 91779
},
{
"type": "playerAchievement",
"character": "Osmoses",
"timestamp": 1368470700000,
"achievement": {
"id": 6193,
"title": "Level 90",
"points": 10,
"description": "Reach level 90.",
"rewardItems": [
{
"id": 87764,
"name": "Serpent's Heart Firework",
"icon": "inv_misc_missilelarge_green",
"quality": 1,
"itemLevel": 1,
"tooltipParams": {
},
"stats": [
],
"armor": 0
}
],
"icon": "achievement_level_90",
"criteria": [
],
"accountWide": false,
"factionId": 2
}
},
Basically i need to loop over everything in "news" and output it.
What I can't figure out how to parse it correctly :
A : without specifying key numbers and
B : when it gets to a key that then contains further keys and further arrays under those keys i'm at a loss. (E.g. the "player achievement" key)
I appreciate I'm probably being a bit newbie here and could quite possibly be on page 1 of "php for dummies" but i swear I've googled it to death!
See if this approach could fit. Be sure your JSON array is properly formatted though.
$test = the_json_array;
$array = json_decode($test,true);
function recursive($array) {
foreach($array as $key => $value) {
if (!is_array($value)) echo $key.":".$value."<br/>";
else recursive($value);
}
}
recursive($array);
SEE json_decode
Dont forget to give second argument as TRUE otherwise it will return object
and try something like this
$json = 'your json'
$json_array = json_decode($json,true);
$news = $json_array['news'];
foreach($news as $value)
{
print_r($value);
}
I think for your purpose you should have look at array_walk_recursive
function printResult($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($news, 'printResult');
yo need to do json_decode('your-jason', True) it will convert your Json string to Array.
Json_decode for more understanding
if you don't specify TRUE in jason_decode function then it will return php object
Hope answer the question. regards

Categories