Pbk1303
Pbk1303

Reputation: 3802

How to write a simple array in json?

I have an array

var array_list=["apple","orange","cat","dog"];

How do i write this in json?

I saw tutorials in w3schools but it showed that json has name value/pairs,should we always write it in name/value pairs or is there a simpler format?.

Upvotes: 0

Views: 9693

Answers (4)

Arvin
Arvin

Reputation: 92

You can convert the array into json by JSON.stringify

var array_list=['apple','orange','cat','dog'];
var json_string = JSON.stringify(array_list);

And using JSON.parse you can parse the JSON

var obj = JSON.parse(json_string);

DEMO

Upvotes: 3

trvrm
trvrm

Reputation: 814

An array is a perfectly legal JSON serializable object.

var array_list=["apple","orange","cat","dog"];
var json_string = JSON.stringify(array_list);

Upvotes: 1

Barmar
Barmar

Reputation: 781706

The JSON for that array is:

["apple","orange","cat","dog"]

JSON for arrays is the same as Javascript array literals, except that JSON doesn't allow missing elements or an optional trailing comma. And the elements of the array have to be valid JSON, so you have to use double quotes around strings, you can't use single quotes like Javascript allows.

You generally shouldn't have to worry about how to format JSON yourself, most languages have library functions that do it for you. In JS you use JSON.stringify, in PHP you use json_encode().

Upvotes: 4

gnasher729
gnasher729

Reputation: 52592

You use name/value pairs for dictionaries. You use a sequence of values for arrays.

{ "name1": 1, "name2": "text" }
[ 1, 2, 3, "apple", "orange", 3.2 ]

Upvotes: 1

Related Questions