Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON conversion in javascript

I'm trying to stringify a multi-array variable into a JSON string in Javascript. The

//i'm using functions from http://www.json.org/json2.js

var info = new Array(max);
for (var i=0; i<max; i++) {
  var coordinate = [25 , 32];
  info[i] = coordinate;
}
var result = JSON.stringify(info);

But result doesn't look like a JSON string at all. What am I doing wrong here?

like image 493
Hectoret Avatar asked Sep 19 '25 22:09

Hectoret


2 Answers

You, and many in this question, are confused about the JSON specification. The string you have is a valid JSON array.

From json.org

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Your example matches the second structure - the ordered list of values.

Also from json.org:

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Doesn't leave much to the imagination. You've got a valid JSON array there. Have fun with it. But just to be annoyingly thorough:

From the RFC

RFC 4627, Section 2

2) JSON Grammar

A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.

A JSON text is a serialized object or array.

  JSON-text = object / array
like image 105
Kenan Banks Avatar answered Sep 21 '25 13:09

Kenan Banks


The result looks like this for me:

[[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32]]

Which is fine as far as I can see. It might look a bit weird, but that is mostly because JSON is used a lot for objects, which have a slightly different notation. You can eval the string and get the array structure back though, so it looks fine to me.

like image 22
ylebre Avatar answered Sep 21 '25 14:09

ylebre