Use JSON data in JavaScript

  • 2020-12-19 20:53:30
  • OfStack

JSON is the JavaScript native format, which means that no special API or toolkits are required to process JSON data in JavaScript.

JSON grammar

JSON is constructed in two structures:

Object - A collection of name/value pairs. In different languages, it is understood as objects, records, structures, dictionaries, hash tables, lists of keys (keyed list), or associative arrays. 1 object begins with "{" (left parenthesis) and ends with"} "(right parenthesis). Each "name" is followed by a ":" (colon); Use ", "(comma) between" name/value "pairs.

Array - An ordered list of values. In most languages, it is understood as an array. An array begins with "[" (left center bracket) and ends with"] "(right center bracket). Values are separated by ", "(comma).

The JSON has no variables or other control structures. JSON is for data transfer only.

Assign JSON data to a variable

For example, you can create a new JavaScript variable and then assign a data string in JSON format directly to it:


var people =
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}

It's very simple; people now contains the data in JSON format you saw earlier. However, this is not enough, as the way to access the data does not seem obvious yet.

To access the data

Although it may not seem obvious, the long string above is actually just an array; Once you put this array into the JavaScript variable, you can easily access it. In fact, you can just represent the elements of an array using a period notation. So, to access the last name of the first entry in the programmers list, just use the following code in JavaScript:


people.programmers[0].lastName;

Notice that the array index starts from zero. So, this line of code first accesses the data in the people variable; Then move to the entry called programmers, and then to the first record ([0]); Finally, access the value of the lastName key. The result is a string value of "McLaughlin".

Here are a few examples of using the same 1 variable.


people.authors[1].genre 
// Value is "fantasy"
people.musicians[3].lastName 
// Undefined. This refers to the fourth entry,and there isn't one
people.programmers[2].firstName 
// Value is "Elliotte"

With this syntax, you can process data in any JSON format without using any additional JavaScript toolkits or API.

Modify the JSON data

Just as you can access the data with periods and parentheses, you can easily modify the data in the same way:


people.musicians[1].lastName = "Rachmaninov";

After converting the string to an JavaScript json format object, you can modify the data in the variable like this.

Note: Objects in json format are different from json text


var obj={name:"  zhang 3 ","sex":'  male  '}; //json  Formatted object 
var str=" { name: "  zhang 3 " , "sex" : '  male  ' }" ; //json  Formatted string (  json  Formatted text) 

Convert back to string

Of course, if you can't easily convert an object back into the text format mentioned in this article, then all the data changes won't be of much value. In JavaScript this conversion is also simple:


var newJSONtext = people.toJSONString();

That's it! You now have a text string that can be used anywhere, for example, as a request string in an Ajax application.

More importantly, any JavaScript object can be converted to JSON text. Not only can you handle variables originally assigned with the JSON string. To convert an object named myObject, you simply execute the same form of command:


<script type="text/javascript">
function Car(make,model,year,color)
{
this.make=make; 
this.model=model; 
this.year=year; 
this.color=color;
} 
function showCar()
{
var carr = new Car("Dodge","Coronet R/T",1968,"yellow"); 
alert(carr.toJSONString()); 
}
</script>

This is the biggest difference between JSON and other data formats. If you use JSON, you just call a simple function and get formatted data ready to use. For other data formats, you need to convert between the raw data and the formatted data. Even if you use an API like Document Object Model (which provides functions to convert its own data structures to text), you need to learn this API and use API objects instead of using the native JavaScript objects and syntax.

The bottom line is that if you're dealing with a large number of JavaScript objects, JSON is almost certainly a good choice so that you can easily convert the data into a format that you can send to a server-side program in a request (Ajax).

Methods for converting JSON strings to JSON objects

To use str1 above, you must first convert to an JSON object using the following method:


// by JSON String converted to JSON object 
var obj = eval('(' + str + ')');

or


var obj = str.parseJSON(); // by JSON String converted to JSON object 

or


var obj = JSON.parse(str); // by JSON String converted to JSON object 

Then, you can read:


people.programmers[0].lastName;
0

Special note: If obj is originally an JSON object, then the conversion using the eval () function (even for multiple conversions) is still an JSON object, but the processing using the parseJSON () function is problematic (throwing syntax exceptions).


Related articles: