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
Related
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'm trying to extract the value from the event key (delivered) using PHP. I thought the follow would work below but I'm getting no results. I know this is probably a simple thing to do and probably looking too far into it.
How I am trying to extract the value
$status = json_decode($status, true);
echo $status[1]['event'];
Here is my JSON file
{
"events":[
{
"email":"email#gmail.com",
"date":"2020-02-17T22:16:58.000+01:00",
"subject":"PHPMailer SMTP test",
"messageId":"<hdskjfjsdhfsjdkfdksh>",
"event":"delivered",
"tag":"",
"from":"test#gmail.com"
}
]
}
Any help would be appreciated :)
The first issue is that your JSON file is wrong formatted. It should be:
{
"events": [
{
"email": "email#gmail.com",
"date": "2020-02-17T22:16:58.000+01:00",
"subject": "PHPMailer SMTP test",
"messageId": "74483437597589347843758934759",
"event": "delivered",
"tag": "",
"from": "test#gmail.com"
}
]
}
Second, $status[1]['event'] is also wrong. You should use $status['events'].
I figured it out. So I am parsing a json response from CURL...
$response = curl_exec($curl);
I changed this
$status = json_decode($status, true);
echo $status['events'][0]['event'];
to
$status = json_decode($response, true);
echo $status['events'][0]['event'];
I totally missed that mistake. Thanks to everyone who reach out!
I'm trying to put a users "favourite" game into the corresponding file for their user upon post.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
The file is structured as:
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
}
]
Currently it will add the correct data however not into the array, but onto the end.
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
},
{
"CNR": {
"favourite": "game"
}
}
]
I've tried things like arraypush, splice and other methods however I'm not sure what is the best for this use case.
Any thoughts/recommendations on how I can best achieve this with the desired result are greatly appreciated, thanks!
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
Difference is that I moved [] to the end of the $arr_data.
Before adding it to array, you need to check if the key exists and then proceed rather than just adding the code.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
// changes over here
if(isset($arr_data[$_SESSION['username']])){
if(isset($arr_data[$_SESSION['username']]['favourite'])){
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
} else {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
} else {
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
}
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
I can see that most have answered the question but might I also provide some suggestions (food for thought) on your process?
1). Firstly, I can't work out if you are storing ALL users in a single file or if there's a file per user. Example username.json
I am going to assume there is a file per username because there should be to make file writes quicker and it would require the main file to be locked for everyone else just because one user is writing to it.
2). I noticed that the favourite part seems to be stored in the _SESSION too. If the _SESSION is storing the same mini array in it (a replica of what is stored in the file) then there's no point in opening the file to write a single value and then save it again. You may as well just write over the existing file straight away. Like this...
$writeToFile = json_encode($_SESSION[mydata]);
$fh = fopen("/path/to/username.json","w+");
fwrite($fh,$writeToFile);
fclose($fh);
// You could also use file_put_contents but most prefer
// to use fopen()
3). I will assume the passwords you are storing are encrypted and nobody can type [yourdomain]/users/username.json to see the raw output of the json files. You might want to ensure .json files aren't accessible from the browser. You can do that with .htaccess.
Problem is in this code, you are creating every time a new sub array:
Change this:
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
To this
if(isset($arr_data[$_SESSION['username']])) {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
I am struggled at this point.
I am using the script for inserting/updating website languages.
The main structure of the JSON file looks like this
{
"English": {
"shortcode": "EN"
}
}
Here is a sample of the code I am using to insert a language into my JSON file
$data['french'] = $_POST;
array_push($json, $data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
But when I insert a new record into my JSON file new key appends in my JSON file and it looks like this,
{
"English": {
"shortcode": "EN"
},
"0": {
"French": {
"shortcode": "FR"
}
}
}
So my question is how can I insert a new record but to not insert the key "0", "1"..
Thanks in advance.
You only have to make $json[key] = value
$json['French'] = $_POST;
If it does not exist it is added, otherwise it is updated
It seems the $_POST is an array.
So you are pushing an array onto the $json array
Try this:
$json = $json + $_POST;
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.