Hellonearthis
Hellonearthis

Reputation: 1762

Accessing a JSON value that references another JSONs key

I have two JSON files and one references the other.

The first file below is parsed into the program as moves, it's referencing into a spritesheet.

{"stand": { "x":  0, "y": 12, "width": 49, "height": 52 },
 "walk1": { "x": 52, "y": 12, "width": 50, "height": 52 }}

Then I define another object dong as a key value pair like below

doing = { frame: [{sprite:moves.stand, xoff:  0, yoff:102},
                  {sprite:moves.walk, xoff: 10, yoff:102} ]}

And can reference the data as doing.frame[0].sprite.x and all is good.

My problems start when I try to make the doing object as a JSON file as it requires the value sprite to be a string and not an object reference.

{frame:[{"sprite":"moves.stand", "xoff":  0, "yoff":102},
         "sprite":"moves.stand", "xoff": 10, "yoff":122}]}

Is there a way to define an object reference for JSON or a way to convert the string "moves.stand" back into an object reference?

I have managed to use a single word string reference but not a dot syntax reference. But not with the dot notation.

{frame:[{"sprite":"stand", "xoff": 0, "yoff":102},
        {"sprite":"walk0", "xoff": 64, "yoff":102}]}


 moves[doing.frame[0].sprite].x

Upvotes: 0

Views: 2749

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18973

You can save JSON.stringify(doing) content to your file.

var moves = {"stand": { "x": 0, "y": 12, "width": 49, "height": 52 }}


var doing = {
    "frame": [{"sprite":moves.stand, "xoff":  0, "yoff":102},
            {"sprite":moves.stand, "xoff": 10, "yoff":122} ]
}  

console.log(JSON.stringify(doing));

Upvotes: 2

Related Questions