Reputation: 5795
I am creating a JSON object in PHP like this:
echo json_encode(array("results" => array(array("user" => $member['user']),array("company" => $member['company']))));
In the JavaScript I get something like:
"{"results":[{"user":"David"},{"company":"something"}]}"
Then I try to validate this JSON and it is not valid, but when I remove double quotes at the beginning and at the end then it is validate JSON.
What am I doing wrong? This is how it should be:
{"results":[{"user":"David"},{"company":"something"}]}
EDIT:
part of my AJAX call:
success: function(response)
{
for(var i=0;i<response.results.length;i++)
{
sessionStorage.setItem('user',response.results[i].user);
sessionStorage.setItem('company',response.results[i].company);
}
}
Upvotes: 2
Views: 4456
Reputation: 1230
It seems like ur copying the string with the quotes from somewhere (from a log or something?), and trying to validate somewhere else. echo json_encode(..)
should give u the correct Json string!
Upvotes: 0
Reputation: 3641
echo json_encode(
array(
"results" =>
array(
array("user" => $member['user'], "company" => $member['company'] ),
array("user" => $member['user2'], "company" => $member['company2'] )
)
)
);
Upvotes: 0
Reputation: 324610
You appear to be double-encoding it. Either that, or you're encoding it and then dumping it inside quotes.
To be clear, you should have something like this:
var myJSobject = <?php echo json_encode(...); ?>;
Then it's good to go, nothing else needed.
Upvotes: 9