Select json multi-layer data in php - php

My json file like:
{"c_d0_source": "AS-IISNRL",
"num_of_records": 4921,
"source": "last-all-airbox by IIS-NRL",
"version": "2020-05-10T17:01:36Z",
"descriptions": {"URL": "https://pm25.lass-net.org/data/description.json",
"c_d0_method": "method/days/distance(km)",
"c_d0": "calibration PM2.5 (ug/m3)"},
"feeds": [{"c_d0_method": "BRR/14/10.74",
"gps_lat": 24.37755,
"gps_num": 9.0, "s_d1": 0.0},
, {"c_d0_method": "BRR/14/10.74",
"gps_lat": 24.34755,
"gps_num": 9.0, "s_d1": 0.0}]}
I want to get all the information of "feeds" in "descriptions".
This is my php, and
my information is from api :
<?php
$fp = gzopen("https://pm25.lass-net.org/data/last-all-airbox.json.gz", "r");
if ($fp){
$data = array();
$arr =" ";
$lines = gzfile('https://pm25.lass-net.org/data/last-all-airbox.json.gz');
foreach ($lines as $line) {
$arr = $arr.$line;
}
$obj = json_decode($arr);
echo $obj->{"descriptions"}->{"feeds"};
}
else {
echo ("fail");
}
?>
The output is :
Undefined property: stdClass::$feeds .
How can I get this data?

Your JSON is not valid. When you fix the double comma issue, you'll notice that your "feeds" property is not inside the "description" property. It's on the same level, so use $obj->feeds directly.
Try to use "JSON formatter" to detect the problem next time.

Related

Data Not getting Added to JSON using PHP

After thorough research I have not been able to find the solution of a simple problem of appending an object to my JSON.
{
"menu": {
"parentmenu1": {
},
"parentmenu1": {
"pm_name": "iceberg 98 ",
"pm_time": "icebeest-98"
}
},
"projectname": "project1",
"place": "gzb",
"firstlogo": "flogo",
"logo": "logo",
"colordirection": "TopLeft",
"color1": "color1",
"color2": "color2",
"fontcolor": "fontcolor"
}
And my PHP code looks like this
<?php
$parentmenu="Sixty";
$childmenu= "hell";
$grandchildmenu= "icebeest";
$parentmenu1="PUSH Approach-98";
$childmenu1= "iceberg 98 ";
$grandchildmenu1= "icebeest-98";
$data = file_get_contents('format.json');
$json_arr = json_decode($data, true);
//$json_arr['menu']=array($parentmenu2);
$parentarray = array('pm_name'=>$childmenu1, 'pm_time'=>$grandchildmenu1);
echo $parentarray['pm_name'];
$json_arr['menu']['parentmenu1'] = $parentarray;
//array_push($json_arr['menu'], $parentarray);
file_put_contents('results_new.json', json_encode($json_arr));
?>
The parentmenu1 gets removed as soon as I re-run the code.
But if I try adding the 2 arrays at once in same file, then it will add.
So please let me find out the way in which I can add data with key to the end of the structure. TIA

JSON to Array using PHP json_decode

I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);

Parsing JSON object in PHP using json_decode

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.

Convert JSON in print format to valid JSON

I have a text file that is formatted like JSON, but in a print/view friendly format and I want to convert that string to valid JSON.
Basically, I want to read the file using PHP5 and call json_decode to deserialize the string.
But, json_decode is not able to parse the "print-friendly" json string.
I am getting error 4 Invalid or malformed JSON.
It looks like someone else had a similar issue as me: PHP json_decode() returns NULL with valid JSON?
I am using notepad++ to write the json file.
So, how can I convert
FROM:
{
"data": [
{
"thumbImg": "thumbImg",
"street": "street",
"city": "Fort Worth",
"state": "Texas",
"zip": "76192-0001",
"url": "url"
}
]
}
TO:
{"data":[{"thumbImg": "thumbImg", "street": "street", "city": "Fort Worth", "state": "Texas", "zip": "76192-0001", "url": "url"}]
I even tried doing the following:
<?php
$filename = "links.json";
$file = fopen($filename, "r");
$lines = file($filename);
$data = "";
;
foreach ($lines as $line_num => $line) {
$formatted = trim($line);
$formatted = str_replace("\r", "", $formatted);
$formatted = str_replace("\n", "", $formatted);
$data .= $formatted;
}
$json = json_decode($data, true);
?>
I did a var_dump of the resulting json string and http://jsonlint.com/ marked it as valid json; however, json_decode is not able to deserialize the json string for some reason.
Thank you!
SOLUTION
I set the encoding of the text file to UTF-8 without BOM and it works fine now. thank you all!
<?php
$filename = "links.json";
$file = file_get_contents($filename);
$json = json_decode($file, true);
?>
References:
- file_get_contents()
- json_decode()

PHP: JSON decoding problem

<?php
$handle = fopen("https://graph.facebook.com/search?q=sinanoezcan#hotmail.com&type=user&access_token=2227472222|2.mLWDqcUsekDYK_FQQXYnHw__.3600.1279803900-100001310000000|YxS1eGhjx2rpNYzzzzzzzLrfb5hMc.", "rb");
$json = stream_get_contents($handle);
fclose($handle);
echo $json;
$obj = json_decode($json);
print $obj->{'id'};
?>
Here is the JSON: {"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}
It echos the JSON but I was unable to print the id.
Also I tried:
<?php
$obj = json_decode($json);
$obj = $obj->{'data'};
print $obj->{'id'};
?>
Note that there is an array in the JSON.
{
"data": [ // <--
{
"name": "Sinan \u00d6zcan",
"id": "610914868"
}
] // <--
}
You could try $obj = $obj->{'data'}[0] to get the first element in that array.
data is an array, so it should be:
print $obj[0]->{'id'};
It looks like the key "data" is an array of objects, so this should work:
$obj = json_decode($json);
echo $obj->data[0]->name;
Have you tried $obj->data or $obj->id?
Update: Others have noted that it should be $obj->data[0]->id and so on.
PS You may not want to include your private Facebook access tokens on a public website like SO...
It's a bit more complicated than that, when you get an associative array out of it:
$json = json_decode('{"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}', true);
Then you may echo the id with:
var_dump($json['data'][0]['id']);
Without assoc, it has to be:
var_dump($json->data[0]->id);

Categories