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

  • google plus

In Brief...

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.

Instructions

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 Training

Categories

Courses

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss