Search code examples
phpjavascriptjqueryjsonstringify

Creating JSON in javascript


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?


Solution

  • 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