How should I encode this data as JSON in javascript?
I use javascript to get an arbitrary number of 'tags' on photos. Each tag has a firstname and a lastname in this form:
firstname = 'john';
lastname = 'doe';
firstname = 'jane';
lastname = 'smith';
I want to encode this data as JSON, send it to my server with Ajax, and decode it in PHP.
My thought was to create a multidimensional array. Is there a better way to do this?
The output of JSON.stringify() is [{\"firstname\":\"John\",\"lastname\":\"Doe\"},{\"firstname\":\"Jane\",\"lastname\":\"Smith\"}]
. How can I have JSON.stringify() not escape all of the quotes?
JSON is inspired by JavaScript's object syntax, so all you need to do is create an array of objects:
var data = [
{
firstname: 'john',
lastname: 'doe'
},
{
firstname: 'jane',
lastname: 'smith'
}
]
var json = JSON.stringify( data ); // send this object to server
JSON is the way to go
JAVASCRIPT
var data = [{
firstname: 'john',
lastname: 'doe'
},
{
firstname: 'jane',
lastname: 'smith'
}
]
var json = JSON.stringify( data );
Now your JSON string will be
[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Smith"}]
PHP
$arr=json_decode('$jsonVar');
Make sure you put the single quotes cover on the php side. Otherwise PHP won't read this as a string
you can convert your tags into json object
var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);
or
var jsonObj = {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
var obj = $.parseJSON(jsonObj);