Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSON is used


May 08, 2021 JSON


Table of contents


JSON uses

JSON is often applied to scenarios in which response data is encapsulated in a background application in JSON format, and after it is passed to the fore desk page, the JSON format needs to be converted to a JavaScript object, and then the data is used in the web page.

Convert JSON text to JavaScript objects

One of the most common uses of JSON is to read JSON data (as a file or as HttpRequest) from a web server, convert JSON data to a JavaScript object, and then use that data in a Web page.

To make it easier for you to explain, we use strings as inputs (not files).


JSON instance - An object from a string

Create a JavaScript string with JSON syntax:

var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Because the JSON syntax is a subset of the JavaScript syntax, the JavaScript function eval() can be used to convert JSON text to JavaScript objects.

The eval() function uses a JavaScript compiler that parses JSON text and then generates JavaScript objects. The text must be surrounded in parentheses to avoid syntax errors:

var obj = eval ("(" + txt + ")");

Use JavaScript objects in Web pages:

<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>

<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>

Try it out . . .

JSON parser

JSON is used The eval() function compiles and executes any JavaScript code. This hides a potential security issue.

Using the JSON parser to convert JSON to JavaScript objects is more secure. The JSON parser recognizes only JSON text, not compiles scripts.

In the browser, this provides native JSON support, and the JSON parser is faster.

Native support for JSON is included in the newer browsers and the latest ECMAScript (JavaScript) standards.

Web browser support Web software support
  • Firefox (Mozilla) 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
  • jQuery
  • Yahoo UI
  • Prototype
  • Dojo
  • ECMAScript 1.5

Try it out . . .

For older browsers, you can use the JavaScript Library: https://github.com/douglascrockford/JSON-js

Related tutorials

ECMAScript