user2717676
user2717676

Reputation: 99

Reading a decoded JSON Lua table

I'm learning Lua to use as a component in a piece of software I'm working on, and largely it's going to be parsing JSON files.

I'm parsing with http://regex.info/blog/lua/json, and I can io.input a file in and parse it with JSON:decode(io.read("*all")) into a local lua_value just fine; and subsequently JSON:encode_pretty(lua_value) to verify the JSON back out to the console.

I can pull the key of a simple top-level JSON value just fine;

{ "book":"LUA For Dummies int" }

where print(JSON_file["book"]) will return LUA For Dummies as expected.

But when it comes to reading a nested key:

{ "book": [
    
    {"title":"LUA For Dummies"}

]
}

I can't tell from Lua documentation or the JSON parser's source code how nested values (here, "title") get read in to the Lua table. From naive C++ intuition, I'm looking for something like a multidimensional array as in print(JSON_file["book","title"]).

I'm sure it's something simple I'm missing..

Upvotes: 2

Views: 4783

Answers (1)

Michael Anderson
Michael Anderson

Reputation: 73450

If the returned value from JSON:decode is a sensible lua table then all you need is

print(JSON_file["book"][1]["title"])

which can be written nicer as

print(JSON_file.book[1].title)

And if you're coming from a C++ background - watch out - lua arrays are 1 based, rather than 0 based. (Can't count the number of times thats tripped me up.)

Upvotes: 2

Related Questions