Thursday, May 18, 2017

JSON Arrays

Arrays as JSON Objects

Example

"Ford""BMW""Fiat" ]
As you can learn from JSON formatter, Arrays in JSON are almost the same as in JavaScript.
Array values in JSON need to be of type string, number, object, array, boolean, or null.
Array values in Javascript can be all of the above and any other valid JavaScript expression such as functions, dates, and undefined.

Arrays in JSON Objects

Arrays can be values of an object property:
{
"name":"John",
"age":30,
"cars":[ "Ford""BMW""Fiat" ]
}

Access Array Values

Access the array values by using the index number:
x = myObj.cars[0];

LoopThrough an Array

Access array values by using a for-in loop:
for (i in myObj.cars) {
    += myObj.cars[i];
}
Or use a for loop:
for (i 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i];
}


Nested Arrays in JSON Objects

Values in an array can also be another array, or even another JSON object:
myObj = {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford""models":[ "Fiesta""Focus""Mustang" ] },
        "name":"BMW""models":[ "320""X3""X5" ] },
        "name":"Fiat""models":[ "500""Panda" ] }
    ]
 }
Use a for-in loop for each array in order to access arrays inside arrays:
for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].name "</h1>";
    for (j in myObj.cars[i].models) {
        x += myObj.cars[i].models[j];
    }
}

Modify Array Values

Use the index number to modify an array:
 myObj.cars[1] = "Mercedes";

Delete Array Items

Use the delete keyword to delete items from an array:
delete myObj.cars[1];

No comments:

Post a Comment