Get data from JSON with square brackets

  1. What do you want to achieve?
    Get json elements. The json contains square brackets.

  2. What is the issue?

Getting data from json like the first image works.
Getting data from json like the second image does not work.

image

image

I want to get the data of ‘title’. Which should result in ‘test’.

  1. What solutions have you tried so far?
    I tried
print(result.request[1])

Also tried

print(result.request.title)

None worked as expected.

For the second image you should try result.request[1].title

2 Likes

Just to expand on this: Lua does not distinguish between an Array and an Object in syntax, which can be identified in JSON by the square brackets [] and curly braces {}, respectively.

Converting a JSON converts its entire contents to a Lua table, which is defined by the curly braces, and allows for mixing of indices (a Lua table can be both an Array and an Object), so it’s important to remember whether the JSON contained an Array or Object when you want to access an entry.

If you are attempting to access a table with numeric indices, you will need to use the square brackets (e.g. myArray[1]). If you are attempting to access an Object, generally you can just use dot notation (e.g. myObject.myValue). Just be aware that JavaScript Arrays are indexed from 0, and Lua tables are from 1, so accessing the first entry in a JavaScript Array would be entry “0,” and in Lua, the first entry of an Array-like table would be “1.”

So going back to your two screenshots: Your first data set is a simple Object. You can access the children of “context” with the usual dot notation: result.context.title. In the second image, your JSON contains an Array of Objects under the “request” key, so accessing members would require a mix of both square brackets and dot notation: result.request[1].title.

1 Like