Reputation: 1797
I am using the json parser from json.org to handle data from my application. The problem is that the parser cannot handle some json formats.
One request receives the data below.
<?php
$obj = array("cities"=>array("city1","city2","city3","city4","city5"));
echo json_encode($obj);
?>
Results in the json below
{
"cities": ["city1","city2","city3","city4","city5"]
}
the code below handles the above data
var data = json_parse(XMLHttpRequestObject.responseText, function (key, value){
alert(key +' = '+value);
});
The parser fails and throws an error.
Does anyone know how to handle such an object.
Upvotes: 0
Views: 950
Reputation:
I executed the following for a quick test and it seems to work:
var text = '{ "cities": ["city1","city2","city3","city4","city5"] }';
var data = json_parse(text, function (key, value){
document.write(key + ' = ' + value + '<br/>');
});
document.write('result = ' + data);
It recursively walks the structure and the result is this:
0 = city1
1 = city2
2 = city3
3 = city4
4 = city5
cities = ,,,,
= [object Object]
result = undefined
What is in your XMLHttpRequestObject.responseText
field?
Also, aren't you supposed to return a value from your function(key, value)
?
Upvotes: 3
Reputation: 4292
The problem seems to be in your application's json encoding algorithm.
Since you did't specify the application language, I cannot tell you the exact function/method to use, but I suggest you to use standard json encoding techniques instead reinventing the wheel.
For example in php you can use the json_encode
standard function of one of the many encoding libraries in the open source world.
Upvotes: 0
Reputation: 12679
The parser fails because the JSON data is malformed. There are two quotes in front of city3
and the starting quote for city4
is missing.
{
cities: ['city1','city2','city3','city4','city5']
}
Are you in control of the code that generates this output? It looks like it's being built by hand, while if possible it should be generated using a JSON library.
PHP example:
$output = array(
'cities' => array('city1', 'city2', 'city3', 'city4', 'city5')
);
echo json_encode($output);
Output:
{"cities":["city1","city2","city3","city4","city5"]}
Upvotes: 0
Reputation: 449803
You need to put your keys and values into double quotes:
{
"cities": ["city1","city2","city3","city4","city5"]
}
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
You can use jsonlint to validate the code.
Upvotes: 1
Reputation: 6956
I'd wager that the problem lies in your data. The ''
before city3 is wrong.
It would help if you include some information on the error thrown.
Upvotes: 0