Combine 2 JSON string/objects

Hi,

Does anyone know if it is possible to combine 2 JSON’s into 1 in Corona?

Well you could just decode them into tables and then merge the tables.

local table1 = json.decode(json1) local table2 = json.decode(json2)

for k,v in pairs(table2) do      if table1[k] then --if key exists in both tables, then add them together         table1[k] = table1[k] + v     else --else copy the entry into table         table1[k] = v      end end--then re-encode if you need it to be json again local combinedJson = json.encode(table1)  

You’ll need to adjust this depending on what the values in the table are (i.e. you if table1[“stuff”] is a number and table2[“stuff”] is a function then you can’t add them together).

Thanks Alan,

I was actually thinking about doing it this way, were you decode the jsons first and and combine the tables then. I have it working now.

Well you could just decode them into tables and then merge the tables.

local table1 = json.decode(json1) local table2 = json.decode(json2)

for k,v in pairs(table2) do      if table1[k] then --if key exists in both tables, then add them together         table1[k] = table1[k] + v     else --else copy the entry into table         table1[k] = v      end end--then re-encode if you need it to be json again local combinedJson = json.encode(table1)  

You’ll need to adjust this depending on what the values in the table are (i.e. you if table1[“stuff”] is a number and table2[“stuff”] is a function then you can’t add them together).

Thanks Alan,

I was actually thinking about doing it this way, were you decode the jsons first and and combine the tables then. I have it working now.