My Json isn't parsing properly - php

simple script gets a json file, strips out extraneous headers, and tried to access a single key/value with no luck. anyone?
CODE
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos+15);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj->{'name'}."<HR>";
The results are:
original response =
GET
d41d8cd98f00b204e9800998ecf8427e
Mon, 16 Dec 2013 10:36:23 GMT
/targets/32feaf056b8c46e4a6f5500b6289cf59{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"23029749e4984e2d92dbfb5ff44f8834"}
My Trimmed json is:
{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"b427cb1f89544b4c85332ca0ad174848"}
The print_r of the trimmed json prints:
1
using "$obj->{'target_id'}" to get name give me this:

try this:
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos-2);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj['tagret_record']['name']."<HR>";

Simple solution: using "true" in the json_decode converts the object to an associative array. Items inside are then accessed at $Array[$key][key].

Related

How do i access multiple nested json data

I am having issues accessing the nested data from this. I can access the first top level object but not the nested data. Any suggestions, Thnx
{"userInput":{"relaSource":"DailyMed","relas":"has_EPC","drugName":"intuniv"},"rxclassDrugInfoList":{"rxclassDrugInfo":[{"minConcept":{"rxcui":"40114","name":"Guanfacine","tty":"IN"},"rxclassMinConceptItem":{"classId":"N0000175554","className":"Central alpha-2 Adrenergic Agonist","classType":"EPC"},"rela":"has_EPC","relaSource":"DAILYMED"}]}}
my code is as follows (some functions are tests) but i need to access all datapoints..... relaSource, relas, drugName, rxclassDrugInfoList-> rxclassDrugInfo, minConcept, rxcui, name, tty,
<?php
$url = 'https://rxnav.nlm.nih.gov/REST/rxclass/class/byDrugName.json?drugName=intuniv&relaSource=DailyMed&relas=has_EPC'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
echo $data;
echo "<br/>";
$jsonObj = json_decode($data);
echo "<br/>" . $jsonObj->userInput->relaSource;
echo "<br/>" . $jsonObj->userInput->relas;
echo "<br/>" . $jsonObj->userInput->drugName;
echo "<br/>";
echo "A2";
?>
<?php
foreach ($jsonObj as $data) {
$relaSource = $data->relaSource;
$content = $data->relaSource;
?>
<h1> <?php echo $relaSource; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
$rxclassDrugInfoList = $jsonObj['rxclassDrugInfoList'];
echo $rxclassDrugInfoList['rxclassDrugInfo']."<br/>";
/////////////////////////////////////////////////////////////////////////////
<h2>TEST</h2>
<?php
$url = 'https://rxnav.nlm.nih.gov/REST/rxclass/class/byDrugName.json?drugName=intuniv&relaSource=DailyMed&relas=has_EPC'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
// JSON string
//$someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
// Convert JSON string to Array
$someArray = json_decode($data, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["userInput"]; // Access Array data
///////////////////////////////////////////////////////////////////////////////////////////
// Convert JSON string to Object
$someObject = json_decode($data);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->userInput; // Access Object data
// Convert JSON string to Array
$someArray = $someObject[0]->userInput;
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
echo "<br/>";
echo "<br/>";
echo "<br/>";
?>
I know it is just a problem with addressing items that are nested incorrectly.
**Here is all the datapoints that u needed **
<?php
$json = '{"userInput":{"relaSource":"DailyMed","relas":"has_EPC","drugName":"intuniv"},"rxclassDrugInfoList":{"rxclassDrugInfo":[{"minConcept":{"rxcui":"40114","name":"Guanfacine","tty":"IN"},"rxclassMinConceptItem":{"classId":"N0000175554","className":"Central alpha-2 Adrenergic Agonist","classType":"EPC"},"rela":"has_EPC","relaSource":"DAILYMED"}]}}';
var_dump($json);
var_dump(json_decode($json)->userInput);
var_dump(json_decode($json)->rxclassDrugInfoList);
var_dump(json_decode($json)->userInput->relaSource);
var_dump(json_decode($json)->userInput->relas);
var_dump(json_decode($json)->userInput->drugName);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->rxcui);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->name);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->tty);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->rxclassMinConceptItem->classId);
?>

how to echo fixer.io json php

Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;

How to JSON decode with \\n in php

I have a JSON structure as below
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
When trying to extract the text and numbers I can do the first step and it works but the nested JSON has \\n and it does not give the text as output
The PHP code is as below
$result = json_decode($json);
print_r($result);
echo "<br>";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$result_nest = json_decode($value);
echo $result_nest->answerPhrase;
echo "<br>";
Why can I not get the text in answerphrase? It works when the text does not have \\n
You may try the below one. You can replace the \n with some other characters. If you want to display enter in browser then you can replace \n with . Please try the below code and let me know if it worked for you.
<?php
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$result = json_decode($json);
print_r($result);
echo "\n";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$value = preg_replace("/\\n/", "___n___", $value);
$result_nest = json_decode($value);
$result_nest->answerPhrase = preg_replace("/___n___/", "\n", $result_nest->answerPhrase);
echo $result_nest->answerPhrase;
echo "<br>";
}
Prefer to fix json before decode and then decode the sub json.
you could do second step in a loop
function test2()
{
$string = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$json = $this->decodeComplexJson($string);
$number = $json->Number1;
//Put this in a loop if you want
$decodedNumber = $this->decodeComplexJson($number);
var_dump($decodedNumber);
echo $decodedNumber->answerPhrase;
}
function decodeComplexJson($string) { # list from www.json.org: (\b backspace, \f formfeed)
$string = preg_replace("/[\r\n]+/", " ", $string);
$json = utf8_encode($string);
$json = json_decode($json);
return $json;
}

how to get value of id and name from json response

I want to get value of id and name from the string given below in php. Can any body help me please.
string(35400) "{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}
That's not really a valid json (missing ]} at the end), but assuming you removed something from it just to post the question, do it like this:
$json = '{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}]}';
$decoded = json_decode($json, true);
foreach($decoded['cities'] as $v){
echo 'ID: ' . $v['id'] . '<br>';
echo 'Name: ' . $v['name'];
echo '<br><br>';
}
Output:
ID: 3279
Name: Narasaraopet
ID: 1852
Name: Srirangapatna
To use it as objects, you can ommit the second argument, like so:
$decoded = json_decode($json);
Then you'd access the values object-like:
foreach($decoded->cities as $v){
echo 'ID: ' . $v->id . '<br>';
// ...
Read more about json_decode.
Use the function json_decode(), then you'll have an array.

Q: illegal string offset JSON -> PHP

I already view a lot of questions in stackoverflow about my problem, but I didn't find any solution. I don't know where is the problem in my code? I got illegal string offset message at this row:
echo $value["country"] . ", " . $value["competition"] . "<br>";
My full code:
<?php
// file_get_contents call instead
$str = file_get_contents('general.json');
$json = json_decode($str,true);
foreach($json as $key => $value){
echo $value["country"] . ", " . $value["competition"] . "<br>";
}
?>
my json source sample:
["{\"country\":\"America\",\"competition\":\"Copa America\",\"club\":\"BOCA JUNIORS\"}","{\"country\":\"Germany\",\"competition\":\"Bundesliga\",\"club\":\"HANNOVER\"}","{\"country\":\"Asia\",\"competition\":\"JLeague\",\"club\":\"NAGOYA\"}"]
If I view format of the data with var_dump($json) then I see it is an Array. With var_dump($value) then I see there is a string. Please help for me where is the problem in my code, why could not echo value country and value competition?
The problem is that you have json that has been encoded twice, both the array and the elements in the array.
You should avoid doing that, but if you cannot change the source, you need to decode the values as well:
<?php
// file_get_contents call instead
$str = file_get_contents('general.json');
$json = json_decode($str,true);
foreach($json as $key => $value){
// decode the $value string
$value = json_decode($value, true);
echo $value["country"] . ", " . $value["competition"] . "<br>";
}
?>
An example.

Categories