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));
Related
I need to parse a JSON file. I've only worked with XML before.
How can I get the second "food_id" (1730905)?
Here is my JSON file:
{
"shopId":29,
"last":46977914,
"freshfood":[
{
"freshfood_id":2629,
"food":[
{
"food_id":1740851,
"type":"fruit",
"status":1
},
{
"food_id":1730905,
"type":"vegetable",
"status":1
},
]
}
]
}
I tried this, but it does not work.
$string = file_get_contents("food.json");
$json_a=json_decode($string,true);
echo $GetFreshFoodId = $json_a['freshfood'][1]['freshfood_id'];
PHP arrays are zero-based, so that should be:
$json_a['freshfood'][0]['food'][1]['food_id'];
Also, note that the JSON is not entirely valid - you should remove the last comma. (But you might have left out additional records in your example JSON for clarity.)
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 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
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));
What are those #attributes thing I have in my JSON file and how can I read that with JQuery?
The JSON "text" I use is produced with json_encode in PHP from an array of custom objects.
Here's a reduced JSON file:
{ "movies" : [ { "url":"http:\/\/www.youtube.com\/watch?v=Nsd7ZcXnL6k", title":{"#attributes":{"type":"text"},"0":"**Title here**"} ] }
I can read the URL easily with the following code :
$.getJSON(url, function(json){
$.each(json.movies,function(i,item) {
alert(item.url);
});
});
How can I read the title Title here value ?
UPDATE
Well, I still don't know what the #attributes are, but I know why they were in my final JSON file. I was using $sxml = simplexml_load_file($feedURL); to read a XML and then $sxml->title to read a title, wich is not a string apparently but some kind of PHP object.
Instead of
$this->title = $sxml->title
I used
$this->title = $sxml->title . ""
(Ot's converting the object into a string value). Maybe there's a more intelligent way of doing this?
If you have a recent PHP, it supports casting, so you can use
(string)$xml->title
and it'll work.
$.getJSON(url, function(json){
$.each(json.movies,function(i,item) {
alert(item.url);
alert(item.title[0]);
});
});