Im not sure if this would be considered proper format of a json structure. Essentially what Im trying to have is an array of associative arrays. My json data:
{
"notifications": [{
"notificationid": "7hstyans",
"notificationtitle": "Some alert title",
"notificationtype": "SPECIAL ALERT",
"dateCreated": "1502203175"
}, {
"notificationid": "9ksh7dh2",
"notificationtitle": "This is a old notification",
"notificationtype": "OLD ALERT",
"dateCreated": "1502138431"
}, {
"notificationid": "iksnudo3",
"notificationtitle": "new notification",
"notificationtype": "SOME ALERT",
"dateCreated": "1501000523"
}]
}
I am looking for a way to access it such as data.notifications[0]["notificationid"]
Would this be considered the correct format for json and the correct way to access it or what would be the best approach to format this?
Just use json_decode.
Example:
$data = json_decode($jsonString, true);
echo $data['notifications'][0]['notificationid'];
Related
when i use....
var jsonData = JSON.parse(xhttp.responseText);
i get an error => "JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data"
this is my JSON data from a php script
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Can some please help?.... Thanks
A little bit late to the party, but #igniz87 and #Benjamin James Kippax's answers open your website to security issues, and it is so dangerous to follow their example.
As Owasp reads,
ALWAYS RETURN JSON WITH AN OBJECT ON THE OUTSIDE
Hence, so as to be a layer protected from the barbarism of hackers, you need to ALWAYS have the outside primitive be an object for JSON strings. As you can clearly see, the mentioned people's answers do not follow this crucial security rule.
Owasp, moreover, brings an example and says that a JSON like the following is EXPLOITABLE:
[{"object": "inside an array"}]
Yet, the following JSONs are not,
{"object": "not inside an array"}
{"result": [{"object": "inside an array"}]}
You need to remove the duplicate key element and change it in the following way so you will have an object on the outside.
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
Here, actually you should have brought you php code, as the problem is with that php code which is sending the JSON. When you want to send the JSON try to make an array of your data. I do the following way.
$data = [];
foreach ($results as $res) {
$t = [];
$t['oldID'] = $res['oldID'];
$t['oldMain'] = $res['oldMain'];
$data[] = $t;
}
echo json_encode(['results' => $data]);
You'd better send your php code which is lacking here. My php script does not contain all of your code, but it gives you idea how to do it.
I have had the same problem for the past several years.
Sometimes the problem is not related to invalid JSON .. like me now.. the problem is that I must use stringify before JSON.parse
var db = JSON.stringify(data);
var db = JSON.parse(db);
And sometimes in php you must use json_encode($data) correctly.
And sometimes your JSON is not valid ( Online JSON Validator )
The JSON is not valid. If it is possible, you can update the JSON as following
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
And also JSON should not contain duplicate key elements. Also you can club the JSON to JSONArray like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
},
{
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}]
it's not a valid json, you must wrap it in array. the valid json is like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
}, {
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}, {
"results": [{
"oldID": 2,
"oldMain": "Banking Files"
}]
}, {
"results": [{
"oldID": 1,
"oldMain": "Technologies"
}]
}]
take a look at the bracket [ ] at the start and the end of string , and the , to split the object.
this some online json linter here to check if your json is valid.
Your code is invalid.
Your code;
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Your code validated;
[{"results":[{"oldID":5,"oldMain":"News papers"}]},
{"results":[{"oldID":3,"oldMain":"Construction"}]},
{"results":[{"oldID":2,"oldMain":"Banking Files"}]},
{"results":[{"oldID":1,"oldMain":"Technologies"}]}]
The problem is that you had multiple JSON root elements. These also weren't comma separated. They also need wrapping in [], which will turn it into an object. If you don't want to wrap your response in [], you can return the string without the [] and instead do this;
JSON.parse('['+yourreponse+']') which will parse the JSON correctly.
Above answer are correct i.e. your json syntax is incorrect. Correcting your syntax would solved the problem (as suggested)
My case was a little different. I was returning json in response to ajax calls. Those jsons where returned by php using a if else construct. Where I mistakenly omitted one else;
if (!empty($_GET['arg1']))
echo getTrainings($filter, 'arg1');
elseif (!empty($_GET['arg2']))
echo getTrainings($filter, 'arg2');
if (empty($_GET['arg3']))
echo getTrainings($filter, 'arg3');
elseif (empty($_GET['arg4']))
echo getTrainings($filter, 'arg4');
So in fact two json where being returned instead of one, that caused problem for $.parseJSON(result);
var par = $.parseJSON(result);
From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.
I want to decode json string including array and object in PHP. When i decoded with
$array = json_decode($json, true);
print_r($array);
it return NULL. Let me know, the way to decode json in PHP. This is my json string.
{
success: 1,
message: "Successful!",
save_date: "2013-09-11 04:09:26",
test: [
{
test_id: "1",
test_date: "2013-09-12",
test_name: "Test 1"
},
{
test_id: "2",
test_date: "2013-09-11",
test_name: "Test 2"
}
]
}
That's not a valid JSON object. JSON objects must enclose all property names in double quotes:
{ "success": 1, "message": "Successful!" }
PHP provides the handy json_last_error_msg function to tell you that.
There's also the online tool JSONLint to validate JSON strings.
Your JSON is invalid, the property names need to be in quotes too.
Like this:
{
"success": 1,
"message": "Successful!",
"save_date": "2013-09-11 04:09:26",
"test": []
}
Hint: use JSONLint to validate your JSON.
your json string should be like the following :
$sJson = '{"success": 1,"message": "Successful!","save_date": "2013-09-11 04:09:26",
"test": [ {"test_id": "1","test_date": "2013-09-12","test_name": "Test 1"},
{"test_id": "2","test_date": "2013-09-11","test_name": "Test 2"}]}';
Use this
$result=(array)json_decode('your json string');
I think it's working for you
Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...
I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}