How to Send and Receive JSON Data to and from the Server

See JavaScript: Tips and Tricks for similar articles.
Looking to improve your JavaScript skills? Check out Webucator’s JavaScript classes.

The JSON syntax is like JavaScript's object literal syntax, except that it cannot be assigned to a variable. JSON merely represents the data itself. Since JSON is just a string of text, it needs to be converted to an object to be useful inside JavaScript. Likewise, JavaScript objects need to be converted into strings in order to be used as JSON data.

Two functions for working with JSON are built into JavaScript:

  • JSON.parse() - Converts a JSON string into a JavaScript object.
  • JSON.stringify() - Converts a JavaScript object into a JSON string.
The following explains how to send data between the browser and server with JSON.

Send JSON Data from the Client Side

  1. Create a JavaScript object using the standard or literal syntax.
  2. Use JSON.stringify() to convert the JavaScript object into a JSON string.
  3. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable. It can also be sent as raw text using the POST method, but this may create extra work for you on the server-side.

Receive JSON Data on the Server Side

  1. Convert the incoming JSON string to an object using a JSON parser for the language of your choice. At json.org., you'll find JSON parsers for many modern programming languages. The methods available depend upon which parser you are using. See the parser's documentation for details.
  2. Do whatever you wish with the object.

Send JSON Data from the Server Side

  1. Create a new object for storing the response data.
  2. Convert the new object to a string using your JSON parser.
  3. Send the JSON string back to the client as the response body (e.g, Response.Write(strJSON), echo $strJSON, out.write(strJSON), etc.).

Receive JSON Data on the Client Side

  1. Convert the incoming JSON string to an object using JSON.parse().
  2. Do whatever you wish with the object.

Related Articles

  1. How to Install Node.js on a Mac
  2. How to Run a Node.js Application on Windows
  3. How to Send and Receive JSON Data to and from the Server (this article)
  4. How to Run a Node.js Application on a Mac
  5. How to Open Google Chrome's JavaScript Console
  6. How to Create a Google Map Object with the Maps JavaScript API
  7. Why JavaScript is called JavaScript
  8. How to Learn JavaScript on Your Own
  9. How to Install Node.js on Windows