Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between using JSON arrays vs JSON objects? [duplicate]

What are the difference and advantages of using JSON arrays:

{    thing:[      { },      { }    ] } 

versus JSON objects:

{    thing:{      { },      { }    } } 
like image 538
antonpug Avatar asked Sep 05 '12 19:09

antonpug


People also ask

What is the difference between JSON array and JSON object?

JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.

What are JSON arrays used for?

Generally in JSON array are used to store a grouping of like items, while object are used to contain grouping of different properties for a single item. Show activity on this post. JSON is primarily a language that allows serializing javascript objects into strings.

What is the difference between JSON object and JSON string?

It is a common mistake to call a JSON object literal "a JSON object". JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format.


2 Answers

The difference between an array and an object is that

Objects are set up using a key and value like:

person.age = 15; 

If the key value is a variable, then one could access it like:

var key = "age"; alert(person[key]); 

Arrays use an integer[1] index and take a value.

player[1].score += 1000; 

[1] Yes, I know, in JavaScript the integer index is really turned into a string behind the scenes. Ignore that. Think of arrays taking an integer value ESPECIALLY when you think of JSON.

like image 154
Jeremy J Starcher Avatar answered Sep 20 '22 11:09

Jeremy J Starcher


Objects- key and value, Arrays- integer. When do you use this or that?

I think of arrays and objects as "is a/an" and "has a" respectively. Lets use "Fruit" as example.

Every item in fruit array is a type of fruit.

array fruit : [orange, mango, banana]

. Arrays can contain objects,strings, numbers, arrays, but lets deal with only objects and arrays.

array fruit : [orange:[], mango:{}, banana:{}]

. You can see that orange is an array too. It implies any item that goes int orange is a type of orange, say: bitter_orange, mandarin, sweet_orange.

for fruit object, any item in it is an attribute of fruit. thus the fruit has a

object fruit :{seed:{}, endocarp:{},flesh:{}} 

This also implies that anything within the seed object should be property of seed, say: colour,

like image 26
megyewodi Avatar answered Sep 20 '22 11:09

megyewodi