How do js arrays add json data and how do js arrays differ from json

  • 2020-09-16 07:20:25
  • OfStack

JSON (JavaScript Object Notation) is a lightweight data exchange format that USES a completely language-independent text format. JSON is the JavaScript native data format.

Here are two ways to add json data to the js array.

// The first way


personInfo
: [],
for(var i = 0; i < _STAGE.passengerInfoArray.length; i++){
var name = _STAGE.passengerInfoArray[i];
var person = {v:name, text:name};
this.personInfo.push(person);
}

// The second way


var passengerInfo = {};
passengerInfo.psgTypeDesc = psgTypeDesc;
passengerInfo.flightPrice = flightPrice;
_STAGE.passengerInfoArray.push(passengerInfo);

The difference between js array and json

1, the array

1. Define a 1-dimensional array: var s1=new Array();

s1 s1 = [1, 2, 3, 4] or [0] = 1, s1 [1] = 2, s1 [3] = 3, s1 [4] = 4;
alert(s1[0]);

So it's 1;

2,, the definition of the 2-vitamin group: var s1=new Array();

var s1=[[3,1],[2,3,4],3,[4,5,6,7,8]];
alert(s1[1][0]);

So it's 2;

2. Define the json object

1, json object


 var status_process = {
       " name5" : ' Idle period ',
     "name1" : ' Seeding time ',
     "name2" : ' Seedling stage ',
     "name3" : ' Growing season ',
     "name4" : ' Harvest time '
    }    
   alert(status_process);

The results were: Object:Object;

2, json string

The so-called json string means that the value of the string variable is in the same format as json, but is not an json object, such as:


       var s1="{";
       var s2 = " 'name5' : ' Idle period ',  'name1' : ' Seeding time ','name2' : ' Seedling stage ','name3' : ' Growing season ','name4' : ' Harvest time '";
       var s3="}";
       var status_process=s1+s2 +s3 ; 

Although the value of status_process conforms to the format of the json object, it is not an object, just a string (which is patched together);

Convert string to json object using the functions eval, eval("(" + status_process+ ")");

Conclusion: The json string passed in from the background to the foreground is not a real json object, so you need to use the eval function conversion.

3. Use of json objects


var status_process = {
      name5 : ' Idle period ',
     name1 : ' Seeding time ',
     name2 : ' Seedling stage ',
      name3 : ' Growing season ',
      name4 : ' Harvest time '
     };
     alert(status_process["name5"]);
     alert(status_process.name5);

Both are: idle period

4, json2 dimension objects


var status_process = {
 name5 : {name3:' Idle period '},
 name1 : ' Seeding time ',
 name2 : ' Seedling stage ',
 name3 : ' Growing season ',
 name4 : ' Harvest time '
};
alert(status_process["name5"]["name3"]);
alert(status_process.name5.name3);

The result is: 'Idle idle period'


Related articles: