Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript objects vs arrays vs JSON

Tags:

Despite much googling and hair-pulling, I can't for the life of me articulate the difference between json, objects, and arrays (in javascript). Below is how I've been using 2-dimensional data containers (afraid to use the words "array," "object," or "json" here). Please tell me what these two examples are?

//first example: [     {"record_id":1,"name":"Frank"},     {"record_id":2,"name":"Sally"} ]  //second example: { "countries":      [     {"id":1,"name":"Canada"},     {"id":2,"name":"Mexico"}     ], "states":     [     "id":1,"name":"Maine"},     {"id":2,"name":"Alaska"}     ] } 
like image 205
Octavient Avatar asked Oct 06 '12 21:10

Octavient


People also ask

What is the difference between object and array in JSON?

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.

Are JSON objects the same as JavaScript objects?

JavaScript Objects VS JSON Though the syntax of JSON is similar to the JavaScript object, JSON is different from JavaScript objects. The key in key/value pair should be in double quotes. The key in key/value pair can be without double quotes. JSON cannot contain functions.

Is JSON and array same?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null.


1 Answers

JSON is a representation of the data structure, it's not an object or an array.

[1,2,3] 

is an array.

{"foo":"bar"} 

is an object.

In your example,

[   {"record_id":1,"name":"Frank"},   {"record_id":2,"name":"Sally"} ] 

Is an array of objects.

{   "countries":      [       {"id":1,"name":"Canada"},       {"id":2,"name":"Mexico"}     ],   "states":     [       {"id":1,"name":"Maine"},       {"id":2,"name":"Alaska"}     ] } 

Is an object containing other arrays and objects inside of it.

like image 105
Gary G Avatar answered Sep 28 '22 11:09

Gary G