I am making an CMS, Where you have to put in your own JSON data string.
Like this
Then its going to a php file. But in that file I want to split the data string
from something like this:
{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}
to this
["audio", "title", "vraag", "antwoord"]
Using json_decode, care, your JSON string is not correct :
$json_string = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":[0, 1, "a"], "antwoord":["yes", "no", 0]}}';
// Add TRUE to force an array, not an object
$array = json_decode($json_string, TRUE);
print_r(array_keys($array['main_object']));
It works with this code. I tried.
Assuming the following PHP code:
<?php
$JSONData = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}'; //In reality you'll be getting the JSON data from the form rather than assigning it here.
$arrayData = json_decode($JSONData, true);
if ($arrayData !== null
&& is_array($arrayData)
&& isset($arrayData["main_object"])
&& is_array($arrayData["main_object"])) { //JSON was valid and in the correct format
$usableData = array_keys($arrayData["main_object"]);
//Do whatever you need to do with your $usableData
} else {
//Handle badly formatted data here.
}
Related
I have a simple functionality for adding products in JS and I am trying to save this products to a .json file using php.
My json objects in JS look like :
{id: 1474791226069, name: "prod", brand: "yhh", price: "2"}
And my php for saving them in my .json file is the following:
<?php
$data[] = $_GET['data'];
$inp = file_get_contents('products.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
var_dump($jsonData);
file_put_contents('products.json', $jsonData);
?>
Sadly, the result I get in my .json file looks a bit weird :
[["{\"id\":1474721566304,\"name\":\"GGG\",\"brand\":\"GG\",\"price\":\"3\"}"],["{\"id\":1474721570904,\"name\":\"GGGH\",\"brand\":\"GGH\",\"price\":\"4\"}"],["{\"id\":1474721574188,\"name\":\"GGGH\",\"brand\":\"GGHH\",\"price\":\"5\"}"]]
I've found it imposible to, let's say, look for a product by ID and delete or update it.
I know a .json file is not supposed to look like this, so my question is : How to make my .json file to look like a normal .json and still to be able to append new .json records from my JS, aka this:
[
{"id":1,"product":"one", "brand":"blah","price":"1"},
{"id":2,"product":"two", "brand":"blah","price":"2"},
{"id":3,"product":"three", "brand":"blah","price":"3"}
]
So I can be able to add new records, and decode/encode it in a more conventional way?
Please help!
From your comment,
$_GET['data'] is shown in the question, it is a json object like this {id: 1474791226069, name: "prod", brand: "yhh", price: "2"}
When decoding a json object, always pass the second parameter as true to convert the objects into associative arrays. Also, you have to use an additional array, for example, $resultData to achieve the desired result. So the solution would be like this:
$resultData = $tempArray = array();
$data = json_decode($_GET['data'], true);
if(($inp = file_get_contents('products.json')) != false){
$tempArray = json_decode($inp, true);
}
array_push($tempArray, $data);
$resultData[] = $tempArray;
$jsonData = json_encode($tempArray);
file_put_contents('products.json', $jsonData);
var_dump($jsonData);
You should call var_dump($tempArray); after array_push($tempArray, $data);
Maybe problem is at array structure by itself.
A code like this:
$item['id'] = 1474721566304;
$item['name'] = 'GGG';
$tempArray[] = $item;
$jsonData = json_encode($tempArray);
var_dump($jsonData);
results in this output:
string(35) "[{"id":1474721566304,"name":"GGG"}]"
I know I am little bit late, but I figured something out, and this is kinda more convenient and easy to understand. I hope you might get it too. And if in future, people won't understand the accepted code, they will surely understand this.
CODE:
<?php
//load data
$data = file_get_contents($_GET['data']);
//decode json to associative array
$json_arr = json_decode($data, true);
//add data
$json_arr[] = array(
"id" => 3,
"product" => "three",
"brand" => "blah",
"price" => "3"
);
//encode the json and save to file
file_input_contents('products.json', json_encode($json_arr));
print_r(json_encode($json_arr));
?>
OUTPUT:
[
{
"id":3,
"product":"three",
"brand":"blah",
"price":"3"
}
]
I have only added single data, but when you add the other data, you will get the desired results only.
Thanks. I hope it might be useful for somebody in the future. Happy Learning!!
I have sent a JSON object to PHP to query my database and return a resultset, however I am getting some unusual behaviour - my JSON object arrives in my script as:
{ "username": "Bobby", "dob": "2015-02-12T00:00:00.000Z" }
Which looks fine too me, in order to perform operations on that data I know I need to use json_decode so that PHP receives it as an array, however when I perform json_decode($request) the output array is:
{ undefined: 24, Bobby: ["dob"]}
I have never had this happen before, and can't quite get my head around exactly why this is happening
EDIT: My complete operation looks like:
if(isset($request)) {
var_dump($request);
$json = json_decode($request, true);
var_dump($json);
}
The first dump is correct, once decoded I get the skewed output
EDIT: I am sending the JSON object from Angular, but I don't think this should cause any problems, however its the only thing I have done differently to what I have in previous apps:
if (!(userName === undefined) && !(userDob === undefined))
{
var json = { "name" : userName, "dob" : userDob };
// Create POST request to the file in the url, send it to PHP in JSON format
var callback = $http.post($scope.url, json );
callback.success(function(data, status) {
...
});
}
EDIT I don't quite understand why, but using print_f or var_dump was delivering skewed results, however if I simply did:
$json = json_decode($request);
$name = $json->name;
$dob = $json->dob;
echo $name;
echo $dob;
It returns the results I would expect.
I believe you may need quotes around the keys:
{ "username": "Bobby", "dob": "2015-02-12T00:00:00.000Z" }
Give that a try.
That's a JavaScript object. Try:
var json = { "name" : userName, "dob" : userDob };
JSON.stringify(json);
I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?
In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE
use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.
{
"firstName":"sunny",
"religion": {"holly":"1",
"bolly":"colly",
"nolly":"only"
},
"lonely":"money",
"ronney":"leone",
"honey":"bunny"
}
This is my JSON. I want to get all the data from this and to be stored into some php variables or an array.
I Used the following code to extract data from my JSON. I decoded it first and then stored it in an array..
$val_array = json_decode($jsondata, true);
echo $jsondata;
$AAA = $val_array->firstName;
$BBB = $val_array->religion;
$CCC_id = $val_array->bolly;
$DDD = $val_array->nolly;
$CCC_id = $val_array->lonely;
$DDD = $val_array->ronney;
But it didn't give me any output. Then I used this.
foreach($data['val_array'] as $item)
{
echo $item[0];
}
}
No output. Help??
You get this second param wrong:
$val_array = json_decode($jsondata, true);
$AAA = $val_array['firstName'];
OR
$val_array = json_decode($jsondata, false);
$AAA=$val_array->firstName;
Your JSON is not valid. Remove commas after last elements:
{
"firstName" : "sunny",
"religion" : {
"holly" : "1",
"bolly" : "colly",
"nolly" : "only" # Here
},
"lonely" : "money",
"ronney" : "leone",
"honey" : "bunny" # And here
}
You have an error in your JSON :
"nolly":"only",
"honey":"bunny",
remove the ',' at the end of these 2 lines, then json_decode() will return you an array.
And if you want an object, do not pass second argument to json_decode()
json_decode by default returns an object yet since you are setting the second parameter to true, you are given an associative array with the information instead.
It basically comes down to the fact that either you do not need to fill in the second parameter and get the object you want, or you work with arrays when you set the parameter to true.
A little reading on PHP.net will do you good for further reference since their documentation is well presented, usually commented by others with helpful suggestions and quite clean as well!
$val_array = json_decode($jsondata, true);
$m1=$val_array['firstName'];
$m2=$val_array['lonely'];
$m3=$val_array['ronney'];
$m4=$val_array['honey'];
$m4=$val_array['religion']['holly'];
$m5=$val_array['religion']['bolly'];
$m6=$val_array['religion']['nolly'];
BY using this, we don't have to use foreach loops or inner loops for accessing data. Viola!
My Json String looks like this:
Now i wanted to take only value of ID as an Integer:
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
}]
How can i do this?
Try this,
<?php
$json='[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
}]';
$jsonArray=json_decode($json);
echo $jsonArray[0]->Obj->ID;
?>
assuming that your json string is inside a post parameter:
$json_string = $_POST['json'];
using json_decode you can convert a json string to a php object:
$json = json_decode($json_string);
and then access to your ID:
$id = $json[0]->Obj->ID;
if you want to convert the object into associative array just do this:
$json = (array)$json;
and access to your id:
$id = $json[0]['Obj']['ID'];
Decode the json output using json_decode and put true as second parameter. It will give you array output.
$arr = json_decode($json,true);
echo $arr[0]['Obj']['ID'];