Detailed Explanation of javascript Parsing json Format Data Method

  • 2021-08-06 19:52:27
  • OfStack

JSON (JavaScript Object Notation) is a simple data format that is lighter than xml. It is in the JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript. So how to parse json with JavaScript?

First of all, json under popular science 1. In json, there are two structures: objects and arrays.

1 object begins with "{" (left parenthesis) and ends with "}" (right parenthesis). Each "name" is followed by a ":" (colon); "Name/value is separated by" and "(comma). Names are enclosed in quotation marks; Values must be enclosed in parentheses if they are strings, not numeric ones. For example:
var o = {"key": "value"};
An array is an ordered collection of values (value). 1 Array begins with "[" (left bracket) and ends with "]" (right bracket). Values are separated by "," (comma).
var array = [{"name": "tom"}, {"name": "jake"}];
In the data transfer process, json is passed in the form of string, while JS operates on JSON object, so the conversion between JSON object and JSON string is the key.
json String: var str = '{"key": "value"}';
json object: var o = {"key": "value"};

1. Converting an json string to an json object

It can be parsed through the eval () function of JavaScript, and the code is as follows:


<script type="text/javascript">
  var json = '{"key":"value","jian":"zhi"}';
  var obj = eval("(" + json + ")");

  console.log(obj);     // Console return  Object
  console.log(obj.key);   // Console return  value
  console.log(obj.jian);  // Console return  zhi

</script>

Or through the JSON. parse () method, the code is as follows:


var json = '{"key":"value","jian":"zhi"}';
var obj =JSON.parse(json);

console.log(obj);     // Console return  Object
console.log(obj.key);   // Console return  value
console.log(obj.jian);  // Console return  zhi

Since both methods can parse json strings, which one do we use? Before that, let's do a test first:


var value = 1;
var jsonstr = '{"name":"jifeng","company":"taobao","value":++value}';
var json1 = eval('('+jsonstr+')');
console.log(json1);         // Console return  Object
console.log('value: '+ value);    // Console return  value 2

My God, the evel method executes the code in the json string! !

Let's look at the JSON. parse () method again:


var value = 1;
var jsonstr = '{"name":"jifeng","company":"taobao","value":++value}';

var json2 = JSON.parse(jsonstr);
console.log(json2);
console.log('value: '+ value);     
 // Console error report Unexpected token + in JSON at position

Now you know how to choose.

eval () method is extremely insecure, especially when parsing the third party data, the third party data will give you some malicious code or something, and you will not be finished? So JSON. parse () is the right choice, and of course some browsers don't support this approach,
You can download json2.js at https://github.com/douglascrockford/JSON-js/blob/master/json2.js and add it to your hlml.

In addition, there is an jsonStr. parseJSON () method that converts an json string into an json object, which also requires the support of the json2. js package.

2. Convert an json object to an json string

Without saying much, look at the code first:


var json = '{"key":"value","jian":"zhi"}';
var obj =JSON.parse(json);

var str=JSON.stringify(obj);
console.log(str);    
// Console return  {"key":"value","jian":"zhi"}

Here we use the method JSON. stringify (obj) corresponding to JSON. parse (str).

Similarly, a method called obj. toJSONString () converts an json object to an json string, corresponding to jsonStr. parseJSON ().

3. Convert an json character array to an json array

This conversion is the same as string-to-object conversion, except that the json array is manipulated in a slightly different way than the json object. Look at 1 code:


var arrayStr = '[{"name":"tom","age":"18"},{"name":"jake","age":"20"}]';
var arrayObj =JSON.parse(arrayStr);

console.log(arrayObj);     // Console return  Array[2]
console.log(arrayObj[0]);   // Console return  Object
console.log(arrayObj[0].name); // Console return  tom
console.log(arrayObj[1].age); // Console return  20

For json arrays, they can be accessed through subscripts. Because it is an array, it can also be traversed through the for loop.

4. jquery parsing json strings

Simply mention jquery. When using the ajax function of jquery, there is an dataType attribute, which can be set to json or the value returned by the server can be obtained by using the $. getJSON () method, and this return value is an json object, so there is no need to do any more conversion.

Of course, jquery also provides the transformation function $. parseJSON (string); This and the previous JSON. parse () usage is a sample, how to use specific, see personal preferences.


Related articles: