views:

237

answers:

3

I am trying to understand how a single and multidimensional javascript array would appear in JSON. Can anyone help me with an example for each?

+1  A: 

Single-dimensional:

["one", "two", "three"]

Multi-dimensional:

[["one", "two", "three"],
 ["four", "five", "six"]]
Justin Ethier
you're missing a comma in multi-dimensional
Russell Leggett
Good catch! Just added the comma.
Justin Ethier
+1  A: 

Single array of primitive integers:

[1, 1, 2, 3, 5, 8]

Single array of objects:

[
  {
    "title": "hello",
    "msg": "world"
  },
  {
    "title": "stack",
    "msg": "overflow"
  },
  {
    "title": "json",
    "msg": "array"
  },
]

Multidimensional array of primitive integers:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Mirage114
what's the difference..is that a javacript array represented as JSON? If yes, how would the JS array look and how would the same in JSON?
ScG
@ScG: It would help if you provided a little more context regarding what you are trying to store in your "array."The array examples I have listed are usable in JavaScript code as well as JSON-compatible.This link (also provided by other posters) explains it in more detail (first Google result for JSON): http://www.json.orgIf you read the first few paragraphs on that page, you'll see that your question "is that a javascript array represented as JSON?" is a little confusing, because JSON *is* a subset of JavaScript, hence the acronym JSON = JavaScript Object Notation.
Mirage114
In other words, these arrays are written the same way in both JSON and in JavaScript. The difference between the first two examples is only in the types of data that are stored in the array. In the first example, the array is storing integer values. In the second, the array is storing objects (name/value pairs). They are both legitimate JSON and JavaScript arrays. The last multi-dimensional example is an array of arrays, and the example is also legitimate for use as a JSON string and in JavaScript source code.
Mirage114
+1  A: 

I think you should know what's the difference between JSON and a JavaScript Object literal, they can look exactly the same, but there are some semantic differences.

JSON is a language-agnostic data interchange format, proposed by Douglas Crockford on 2006, its grammar differs from the JavaScript Object literals, basically by allowing only string keys and the values MUST be an object, array, number, string, or one of the literal names: false, true or null.

Speaking about arrays, in JavaScript they can hold any type of value, primitive values like String, Number, Boolean, undefined or null, and any type of object, even objects with methods, host objects like DOM elements, Date objects and so on.

The syntax diagrams of JSON arrays and values might help you:

Array

Value

CMS