Gunsela
Gunsela

Reputation: 470

Lua add value to json.decoded data

I am trying to insert new data to json. My json is ;

data = {"one":44,"two":18}



arr_stock = json.decode(data)

The data im trying to insert is ;

result = {"three":5}

How can i do it ?

I tried ;

arr_stock = arr_stock , result

But its not working.

Upvotes: 0

Views: 1315

Answers (1)

Piglet
Piglet

Reputation: 28974

arr_stock.three = 5

you should first ensure that decoding your json string actually succeeded to avoid errors.

About your code:

data = {"one":44,"two":18} is invalid syntax. data must be a string if you want to use it as an argument to json.decode as json.decode will decode a json string into a Lua table.

data = '{"one":44,"two":18}' would be a valid Lua string.

Same for result = {"three":5}

Assuming arr_stock is a table successfully obtained through decoding data, arr_stock = arr_stock + result is nonsense.

You cannot add a table and a string, unless you have implemented a respective metamethod. What you want to do here is to insert a new field to a table and that's done through assignment.

Please refer to the Lua manual https://www.lua.org/manual/5.4/

Upvotes: 1

Related Questions