I have a .json file and I want to append an object to a vector in the file, but I got some errors.
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.
Here is an example of my .json file:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.
What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!
Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.
Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.
So
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
can become simply
array_push($jsonarray['packages'], $myObj);
P.S. You can also remove the warning about "Creating default object from empty value" by writing
$myObj = new \stdClass();
just before the line
$myObj->short = $_POST["short"];
so that you're adding your properties to an object which already exists.
Related
I have this JSON string.
[
{
"name": "user_title",
"value": "Bapak."
},
{
"name": "user_firstname",
"value": "Test"
},
{
"name": "user_lastname",
"value": "XXX"
}
]
This string generated dynamically. It may has more or less. I use JSON Decode to process it in PHP.
$json_form = json_decode($json_string,true);
$user_title = $json_form[0]['value'];
$user_firstname = $json_form[1]['value'];
$user_lastname = $json_form[2]['value'];
How do I check the variable user_title even exist in the string?
If it exist I should get the value but if not that means $user_title = NULL.
You might want to consider mapping your JSON into a key/value array using array_column; then it is easy to check for the existence of a value. For example:
$json_form = json_decode($json_string, true);
$values = array_column($json_form, 'value', 'name');
$user_title = $values['user_title'];
$user_firstname = $values['user_firstname'];
$user_lastname = $values['user_lastname'];
echo "title: $user_title\nfirst name: $user_firstname\nlast name: $user_lastname\n";
Output for your sample data is:
title: Bapak.
first name: Test
last name: XXX
It's also easy to add default values when a key is missing, for example:
$user_title = $values['user_title'] ?? '';
I would like to push new object inside a JSON file with PHP but I don't find any solution on internet due to the format.
Here is my Json file.
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
}
}
}
And here is the php file
$json = file_get_contents('./content.json');
$data = json_decode($json);
$id = "snippet3";
$title= "My title";
I expect to push those new data inside the JSON.
The result should be:
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
},
"snippet3": {
"id":"snippet3",
"title":"My title"
}
}
}
Thank you
$json = file_get_contents('./content.json');
$data = json_decode($json, true); //added true to make it an array
$id = "snippet3";
$title = "My title";
$data['html'][$id]['id'] = $id; //add the id to the array
$data['html'][$id]['title'] = $title; //add the title to the array
$newData = json_encode($data, true); //turn the array back into json
$writeJson = file_put_contents("content.json", $newData); //write the json array to json file
I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:
<?php
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);
if ($array != null) {
$arrNew['ObjID']++;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$arrNew = [];
$array['ObjID'] = 0;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json
{
"0": [],
"1": {
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"3": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"ObjID": 0,
"username": "bob",
"email": "b#doe.com"
}
So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:
Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
Create a JSON main object
Insert 1st object inside the main object
Append a 2nd object (still inside the main object)
And so on with 3rd, 4th, etc..
So I would need to get an output like this:
{ <-- Main Object starts
"1": { <-- 1st object inside the Main Object
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": { <-- 2nd object
"ObjID": 1,
"username": "sarah",
"email": "s#doe.com"
}
} <-- Main Object closes
I can't really figure out what I'm doing wrong in my PHP code.
Logic in the else part should be inverted:
} else {
$array = [];
$arrNew['ObjID'] = 0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
}
Try below code.
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
if($jsonStr=='') $array = array();
else $array = json_decode($jsonStr, true);
if (empty($array)) {
$arrNew = [];
$arrNew['ObjID']=0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$array['ObjID'] ++;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
I want to adding array's to an existing .json file with with a HTML form.
this is my PHP:
$myFile = "data.json";
$newArray = array(
'name'=> $_POST['name'],
'date'=> $_POST['date']
);
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp);
array_push($tempArray, $newArray);
$jsonData = json_encode($tempArray);
file_put_contents($myFile, $jsonData);
this is my JSON:
[
{
"name": "name 1",
"date": "01.02.2017"
},
{
"name": "name 2",
"date": "05.02.2017"
},
{
"name": "name 3",
"date": "05.03.2017"
}
]
The problem is i got the warning
"array_push() expects parameter 1 to be array, null given in..."
and in the JSON there's is only null. What is my problem with my code?
Add a second parameter to json_decode() and set it to true:-
$tempArray = json_decode($fileTmp,true);
array_push($tempArray, $newArray);
Apart from using the associative version of json_decode as already stated in the other answer, I think that the problem is your input json file.
You should check for valid content and create your default array if the json is empty:
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp, true);
if (!$tempArray) {
$tempArray = array();
}
...
I complied code, it works. Check permissions for data.json file.
I have this function in php
<?php function showTable(){
$url = "http://10.0.0.1/lib/api/desk/branch/";
$params = array ("action" => "list","company_key" => "1");
$result=requestURL($url,$params);
$json_a=json_decode(strip_tags($result),true);
?>
This is the json I got from the code above. I need to check the key "status". If it has a value "no", it should display an alert that status is not ok. Thanks!
{
"init": [
{
"status": "ok",
"record_count": 9,
"code": "",
"message": "",
"page_count": null,
"current_page": 0
}
]
}
Easy.
Suppose you hold the JSON in $json.
$jsonDecoded = json_decode($json, true);
if($jsonDecoded['init'][0]['status'] != 'ok') {
print "status is not ok :(";
}
Let say that json is in $json variable
$json = json_decode($json,true);
$status = $json['init'][0]['status'];
if($status=='ok'){
# do something here
}else{
# display not ok here
}