How to Convert a String to JSON

by Kevin Lee

Computers and humans often cannot understand the same language. Computers read binary numbers, and humans understand text. JSON, a text-based protocol, consists of text data that anyone can comprehend. Convert data objects into JSON, send it to another computer, and that computer can decode the data you sent. If your Web application needs to convert a text string into a JSON object, use a JavaScript object to perform this task.

1

Launch an HTML editor or Notepad, and open any HTML document.

2

Paste the following JavaScript code into the document's script section:

var string = '{"make":"Ford","model":"Mustang"}';

var jSONobject = JSON.parse(string);

alert(jSONobject.make + " " + jSONobject.model);

The string variable holds a text object that describes a car. It contains a make, which is "Ford," and a model whose value is "Mustang." The JSON.parse function converts that string into a JSON object and stores it in the variable named jSONobject. The final statement examines the values in the object and displays them.

3

Save your document and view it in a browser. The code converts the string into a JSON object. An alert box shows the values for the make and model variables stored in the JSON object.

Tips

  • check This example creates a variable named jSOnobject. This variable holds the object created by the JSON.parse method. You do not have to give that variable this name. Call it anything you like. Once you create it, examine its values as shown in the sample code.
  • check .

About the Author

After majoring in physics, Kevin Lee began writing professionally in 1989 when, as a software developer, he also created technical articles for the Johnson Space Center. Today this urban Texas cowboy continues to crank out high-quality software as well as non-technical articles covering a multitude of diverse topics ranging from gaming to current affairs.