Suffick
Suffick

Reputation: 651

Variable in JSON

I don't have much experience with JSON, I want to know if something like this is possible.

{
    "variable": "A really long value that will take up a lot of space if repeated",

    "array": [variable, variable, variable]
}

Obviously that isn't valid, but I want to know if there is a way to do this. I tried using "variable" but of course that just sets the array item to the string "variable". The reason I want to do this is I need to repeat long values in a multidimensional array, which takes up a lot of space.

Thanks.

Upvotes: 3

Views: 1567

Answers (4)

Mark Bessey
Mark Bessey

Reputation: 19782

Are you worried about space in the output, or in the object created from the JSON? In the latter case, it's likely that the string values will be coalesced when the parsing happens.

If you're concerned about the size of the JSON, then you'll probably either want to change to another format, or de-duplicate the strings in the JSON.

You could add an object to your JSON data that maps ID numbers to strings, then use the IDs to represent te strings.

Upvotes: 2

Amrendra
Amrendra

Reputation: 2077

you will get your answer here jason tutorial for beginners

example:
  var data={
    "firstName":"Ray",
    "lastName":"Villalobos",
    "joined":2012
  };

Upvotes: 0

Zach
Zach

Reputation: 7930

If you are willing to do some post-processing on the JSON after parsing it, then you can use a token value in your array, and replace the token after parsing with the variable. Example:

{
    "variable": "A really long value",
    "array": ["variable", "variable", "variable"]
}

Then, in your code that parses:

var obj = JSON.parse(str);
for (var i=0; i<obj.array.length; i++)
{
    obj.array[i] = obj[obj.array[i]];
}

Upvotes: 2

R. Tyler Croy
R. Tyler Croy

Reputation: 101

There is no way to do this in pure JSON (full spec here).

If you wanted to do something like that you might want to look into templating tools such as Handlebars

Upvotes: 0

Related Questions