jQuery JSON parse - "Object not defined" - php

Currently working for the first time with JSON and with little experience of jQuery.
I have this function that gets triggered on "success" of $.ajax request:
function(data) {
$.each(data.notifications, function(notifications) {
alert('New Notification!');
});
}
However I get an error in the firebug console stating "object is undefined" "length = object.length".
The JSON response is:
["notifications",[["test would like to connect with you",{"Accept":"\/events\/index.php\/user\/connection?userId=20625101&action=accept","Decline":"\/events\/index.php\/user\/connection?userId=20625101&action=decline"}]]]
I guess it has something to do with the number of []s but the JSON was encoded by PHP using json_encode()
Any help would be appreciated!
Thanks :)

What you have is a JSON Array. I'm guessing you were looking for something like this:
{
"notifications": [
["test would like to connect with you",
{
"Accept": "\/events\/index.php\/user\/connection?userId=20625101&action=accept",
"Decline": "\/events\/index.php\/user\/connection?userId=20625101&action=decline"
}]
]
}
Although I think a better structure would be:
{
"notifications": [
{
"message": "test would like to connect with you",
"Accept": "\/events\/index.php\/user\/connection?userId=20625101&action=accept",
"Decline": "\/events\/index.php\/user\/connection?userId=20625101&action=decline"
}
]
}
This way notification becomes a property of the object, which means you can access it via data.notifications. Otherwise you'd have to access the notifications via data[1] (data[0] would contain the string "notifications" which essentially becomes meaningless).
The following example should give you an idea as far as setting up your data in PHP:
<?php
$array = array(
"notifications" => array(
array(
"message" => "Test would like to connect with you",
"Accept" => "/events/index.php/user/connection?userId=20625101&action=accept",
"Decline" => "/events/index.php/user/connection?userId=20625101&action=decline"
)
)
);
echo json_encode($array);
?>

Your PHP response should actually be:
{
"notifications": [
["test would like to connect with you",
{
"Accept":"\/events\/index.php\/user\/connection?userId=20625101&action=accept",
"Decline":"\/events\/index.php\/user\/connection?userId=20625101&action=decline"
}
]
]
}
Note that with the above, notification is a field inside the object that the string represents. That will allow you to iterate, the way you are doing it with $.each(..).
The way you are doing is it by having an array (note the initial [ and the last ] in the response). The error is because $.each invokes data.notification.length where .length is an operation on undefined.
PHP side code should be somewhat like below:
echo json_encode(array("notifications" => $notifications));
instead of (my guess):
echo json_encode(array("notification", $notifications));

Related

Error accessing an object property in an array

I am trying to access value of 'user' in the array below. I can't seem to get anything to show. This is my code:
$data = json_encode($values);
When I var_dump the above code, I get the below:
[
{
"user": "xxxx",
"category": "xxxx",
"email": "joe#gmail.com"
}
]
Now I want to get value of 'user' and I did this:
echo $data[0]->user;
But this does not show anything.
Please what am I doing wrong?
As your using json_encode($values) to give you $data, $data is just a string - the JSON you show in the question, and $data[0]->user doesn't work on a string.
If you want the value of user, you should use your original data, I'm assuming $values...
echo $values[0]->user;

echo results from an google safe browsing api array

I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.
var_dump($google_check);
returns the following:
string(488) "{
"matches": [
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
},
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
}
]
}
"
I want to echo results from the array, so something like
echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];
Problem is this returns illegal offset on matches and threat, and only echo's a single character {
What am I doing wrong? How do I echo the results from this array without dumping the entire array?
The response you recieved is in json so you'll need to first json_decode the response.
$decoded = json_decode($google_check, true);
Then you can access it like an array
echo $decoded['matches'][0]['threat'];
echo $decoded['matches'][1]['threat'];
if you want the url value you'll need to do it like this.
echo $decoded['matches'][0]['threat']['url'];
echo $decoded['matches'][1]['threat']['url'];
please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).
Here's a quick explanation on json
https://www.tutorialspoint.com/json/json_php_example.htm

PHP Only Returning Last JSON Object

I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason json_decode is only returning the last item in the JSON array. Here's the JSON:
{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}
And the PHP:
<?php
//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);
var_dump($filey);
?>
The result is only the last item in the array:
array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)
Using json_last_error returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.
I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?
That's because your json object names "person" within json array are similar so json decode will override the values with latest.
Consider something like
{
"person1": {
"lname": "smith",
"fname": "bob"
},
"person2": {
"lname": "jones",
"fname": "jane"
}
}
and your code will work fine.
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true) will give me the array shape I expect.
Happy coding.
When you use json_decode(true), your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true), then change "person" to "person1" or so.
Try both var_dump($filey) and var_dump($json), you will see what I'm talking about.

parse Javascript json into php

Here is my Json. This ia an dwr response ( a webservice created in java) .
{
key1 : {
date : "Today" ,
items : [
{
itemKey1 : "itemValue1",
itemKey2 : "itemValue2",
},
{
itemKey1 : "itemValue1",
itemKey2 : "itemValue2",
},
]
}
}
JSON LINT is also showing the error.
If you can see key do not have "" may be that's why i can not parse it to json in php directly. Is there any way oi can parse it to json and then to array or directly to an array.
But when i transfor this to this type of json it. In JSON LINT it shows that it is proper json.
{
"key1": {
"date": "Today",
"items": [
{
"itemKey1": "itemValue1",
"itemKey2": "itemValue2"
},
{
"itemKey1": "itemValue1",
"itemKey2": "itemValue2"
}
]
}
}
So is there anyway i can trasnfer json to second type. Dynamically in PHP
Since there is no javascript parser build in to PHP and what you have here is JAVASCRIPT and not JSON, your only options is really to implement your own parser / use an existing parser. OR wrangle your string into being JSON, this COULD be done with something like regex, though it will most likely be flaky.
For your specified example data, this would do:
<?php
$data = json_decode(preg_replace_callback('#(\S+)\s*:#i', function($matches){
return '"'.$matches[1].'" :';
},$str));

json_decode corrupts my JSON object

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);

Categories