I get the json data using cURL as an input:
curl -H "Content-Type: application/json" -X GET http://localhost:8000/jsontest --data-binary #test.json
It is simple json with couple of fields:
{
"id": "12345",
"blockId": "9000",
"spot": {
"id": "7890",
"length": 23,
"name": "test",
"country": "de"
},
"channel": "tv:rtl.de",
"startTimestamp": "1323872435345",
"endTimestamp": "13243498394384329"
}
And this is my code for getting the data and storing in database:
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $test["spot"]["id"];
$tvib->name = $test["spot"]["name"];
$tvib->channel = $test["channel"];
$tvib->start = $test["startTimestamp"];
$tvib->end = $test["endTimestamp"];
$tvib->save();
}
var_dump($json_a);
}
When I run cURL request I get this error and a lot of html and js code:
ErrorException: Illegal string offset 'spot' in file TestController.php on line 18 ($tvib->spotid = $test["spot"]["id"];)
If I run this locally like this:
$string = file_get_contents('test.json');
everything works fine. But there is obviously problem with php input.
Any suggestions?
PS I use Laravel 5.5
not need foreach. so change code to :
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
//foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $json_a["spot"]["id"];
$tvib->name = $json_a["spot"]["name"];
$tvib->channel = $json_a["channel"];
$tvib->start = $json_a["startTimestamp"];
$tvib->end = $json_a["endTimestamp"];
$tvib->save();
//}
var_dump($json_a);
}
Related
I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()
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.
I have the following data from an api call:
$userId = 1234; and $accessToken = 6789;. I want to write this to a json file called users.json.
Following this I make another api call and receive the following data:
$userId = 5678; and $accessToken = 0123;.
I then want to add this to the json file so that it looks like this:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
},
]
My code for writing to the json file looks like this. The $userId and $accessToken are defined elsewhere and are returning the correct values:
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
print_r($tempArray); // this doesn;t show anything as the users.json file contains `null`
array_push($tempArray, $userId);
array_push($tempArray, $accessToken);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
Unfortunately this isn't working. When I view the json file it just contains null Can anyone see any error with my code?
Thanks Raul
Your code is wrong. Correct it to look like this
<?php
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
if(empty($tempArray)){
$tempArray = [];
}
$newData = [
"userId" => $userId,
"accessToken" => $accessToken
];
array_push($tempArray, $newData);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
This will definitely work.
You need to to json_decode($content, true); to obtain an array and not an object.
See http://php.net/manual/fr/function.json-decode.php
Also the array_push is not correctly called.
It should be : array_push($tempArray, ["userid"=>$userId,"accesstoken" => $accessToken]);
You have error in json file so that all suggesion not working remove , at end of array. Then try below code :
Your json file should be:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
}
]
php :
$content = file_get_contents('user.json');
$tempArray = json_decode($content,true);
$new_array = array("userId"=>$userId,"accesstoken"=>$accessToken);
array_push($tempArray, $new_array);
$jsonData = json_encode($tempArray);
file_put_contents('user.json', $jsonData);
I am trying to get my data from a json file with php
<?php
$url = 'path/to/my/file.json';
$data = file_get_contents($url);
$characters = json_decode($data);
echo $characters[0]->name;
?>
I got the message
Notice: Trying to get property of non-object
when I do the echo.
Somebody can help me with this?
file.json
[
{
"name": "Aragorn",
"race": "Human"
},
{
"name": "Legolas",
"race": "Elf"
},
{
"name": "Gimli",
"race": "Dwarf"
}
]
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);