Json file parsing in PHP - php

I'm trying to parse the following Json file:
{
"Itineraries" : [{
"date1" : "20/Jan/2016",
"date2" : "20/Jan/1996",
"Options" : [
{
"Num_ID" : [398],
"Quotedwhen" : today,
"Price" : 330.00
}
]
}
]
}
I'm using the following PHP code:
$json2 = file_get_contents("data.json");
var_dump(json_decode($json2));
$parsed_json2 = json_decode($json2);
$price = $parsed_json2->{'Itineraries'}->{'Options'}->{'Price'};
And I get the following error (Line 35 is the last line of the PHP code above):
Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35
Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35
Do you have any idea of how to solve this problem?

You have to put the string
today
In double qoutes
"today"
Because its a string :)

the reason you are getting that message is because the json_decode() is failing to return an object because your JSON is invalid. You need to put double quotes around today. You are also accessing the data incorrectly.
Here's the correct code to get the price:
echo($parsed_json2->Itineraries[0]->Options[0]->Price);
You have created a lot of arrays here which only have one item in them, are you intending to have multiple itinerary, multiple options objects, and multiple Num_IDs per options object? If not you can get rid of a lot of those square brackets.

Related

Read a JSON data value with mixed number and letter in key in PHP

I am stuck with this issue. I am trying to read data from openweathermap.org weather data API. One of the values, rainfall amount, is keyed with a digit and letter in the key. And PHP is throwing errors at me if I try to read it. Here is the code I'm trying to use.
$rainAmount = $data->hourly[$hour]->rain->1h;
and here is the JSON file (a portion of it anyways).
"rain": {
"1h": 1.78
}
This is data provided by the API so I can't just change the key that's used. Here is the PHP error
PHP Parse error: syntax error, unexpected integer "1", expecting identifier or variable or "{" or "$" in /home/
It's pretty obvious it is the digit in the key that is the issue. But how else do I read the value?
Thanks in advance.
Did you try:
$string = '{
"rain": {
"1h": 1.78
},
}';
$arr_weather = json_decode($string, true);
print $arr_weather['rain']['1h'];
The second parameter from json_decode(,, true is a bool to decode the data as an associative array. Please read more here about json_decode:
https://www.php.net/manual/en/function.json-decode.php
If you still want to work with your response as an object you can use the curly braces like this:
$string = '{
"rain": {
"1h": 1.78
},
}';
$weatherObject = json_decode($string);
print $weatherObject->rain->{'1h'};
But in this case, you have to know that if your key is a number only, it will not work, like $weatherObject->rain->{'12'} - So I recommend using the data as an array, like in the first example.

Trying to get multi sub-level JSON using Stripe API [duplicate]

I'm learning a bit of PHP. It's supposed to print 0, however I get an error:
Notice: Trying to get property of non-object in...
<?php
$json = '[{"assetref":"","qty":0,"raw":0}]';
$obj = json_decode($json);
print $obj->{'qty'}; // Result 0
?>
The brackets on the outside of your JSON string are causing it to be an object inside of an array.
You can access the object by specifying which array member you want with $obj[0]->{'qty'};
OR change your json string so it instantiates into an object directly.
$json = '{"assetref":"","qty":0,"raw":0}';

How to store a Json data in one field?

I know this question has been asked a lot and I have researched, trust me.
I have a Json file with multi variables in it. I want to take that Json file and store it in a single BLOB field on MySql Database.
I did json_decode() but when I try to store it, PHP gives me an error because json_decode() returns a php array but bindParam wants a string varaible.
I tried implode(",", json_decode($data,true)) but it didn't work.
Can you help me please...
My JSON file looks like this;
[
{ "xyz": "abc",
"izd": 1
},
{ "xyz": "abc",
"izd": 1
},
{ "xyz": "abc",
"izd": 1
}]
My PHP code is like this;
$json = $_POST["jsonfile"];
$jsondata = json_decode($json,true);
$implodedjsondata = implode(",",$jsondata); // In here, php gets error in impode ( Error : Notice: Array to string conversion)
$Query = $conn->prepare("INSERT INTO table1(somedata) VALUES(:data)");
$Query->bindParam(':data',$implodedjsondata); // In case of not using implode, this line gets error( Error : Notice: Array to string conversion)
$Query->execute();
Thanks...
its already a json? don't do anything with it, insert it as-is. and use bindValue, bindParam is an optimization thing when you have a lot of data you need to change fast when loop-executing a statement..
$json = $_POST["jsonfile"];
$Query = $conn->prepare("INSERT INTO table1(somedata) VALUES(:data)");
$Query->bindValue(':data',$json); // In case of not using implode, this line gets error( Error : Notice: Array to string conversion)
$Query->execute();

Access to the nested items from a JSON structure with foreach PHP produce error

I made this question 3 days ago, but unfurtunaly I couldn't solve my problem till now. I will formulate the question again with the hope that somebody help me.
I have the following JSON structure
{"Id":"1","Persons":[{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},{"Name":"Ben","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
To the element Id is not a problem to access. I can get this value like this:
$arr['Id'] = $_POST['Id'];
echo $arr['Id'];
But if want to access to the structure Persons inside of the JSON, specifically to the Time value of each Person, I do like this:
$arr['Persons'] = $_POST['Persons'];
$jsdecode = json_decode($arr['Persons']);
foreach ($arr['Persons'] as $p){
echo "$p->Time <br/>";
}
And this is the result that get:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>38</b><br />
<br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/><br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/>
Can PLEASE somebody help me?
json_encode() - PHP Array to JSON
The json_encode() method will take a PHP array and encode it as JSON ready to be consumed by an AJAX call.
$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');
$myJson = json_encode($myarray);
echo $myJson;
json_decode() - JSON to PHP Array
json_decode() will take JSON and convert it into a PHP array.
$myJson = '{"Guitar" : "Johnny", "Vocals": "Stephen", "Bass" : "Andy", "Drums" : "Mike"}';
$myarray = json_decode($myJson, true);
print_r($myarray);
You have a syntax error:
{"Id":"1","Persons":[
{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}
]}
no comma before Name Louis.
You should always validate your encoded json on http://jsonlint.com/

Parse JSON File with PHP

I had a problem when parse my json data with php in select html element
This my JSON DATA
This my PHP CODE
Error message :
Notice: Trying to get property of non-object in C:\xampp\htdocs\test\index.php on line 6
This line 6 :
$provider = $jfo->product->provider;
I try to parse "provider" to select html element after someone choose "Jenis Produk".
product is not an object, it is an array:
$jfo->product['provider'];
product is an array, containing multiple products.
$jfo->product[0]->provider;
You'll need to loop through the products.
for ($i = 0; $i < sizeof($jfo->product); $i++) {
$provider = $jfo->product[$i]->provider;
}
It appears that product is not an object.
Have you tried dumping $jfo->product?
My guess is that it is an array.

Categories