简体   繁体   中英

How can I edit and add nested data in json file?

This was just to test though but basically what it does is when it receives a message(message would be like abc/xyz/pq=yo) then makes a out of it like:- {"root":[{"abc":[{"xyz":[{"pq":"yo"}]}]}]} but whet I want is for example there exists a json already and if someone wants to add value like abc/xyz/lm=ayo then if it doesn't exist then it will add that to the existing json. and if someone wants to update something like abc/xyz/pq=ayo then it will update it. That is if there exists a child then it updates a value else it creates it.

in case you are wondering why the json have an array even for a single child ie because in case if we want to add data to particular child we can easily add.

Please keep in mind this was just test code I in readFileResult() but I want to change entire structure.

Update:- as I know the exact path when user wants to add data I can easily add data to that path but the problem is how to check how to check if there exists data? As I've nested child in Arrays('{"root":[{"abc":[{"xyz":[{"pq":"yo"}]}]}]}') I can not loop through each child and parse it coz it would be consuming a lot of resources and time.

Another Update:- I've changed the structure to rfc8259 to get rid of these arrays. This should be simpler but still struggling in "updating" the data.

I found another better way to fix this, I changed the structure a little bit. and Instead of using JSONWriter and JSONArray, I just used JSONObjects to query and edit objects easily. You can check this out.

For inserting objects to JSON if it does not exit or updating if it exists, I think there are multiple ways. Now I don't know your limitations of use case but simplest one would be like below pseudo code :

- get root level json object

- get input from user e.g. abc/xyz/lm=ayo

- split input first by '=' for value at index 1 and then by '/' for keys.

- Now iterate over keys
    + Find in object is key exists.
    + If key exists, get json object for that key and check for next keys inside this object.
    + If key does not exist, add keys in hierarchy and at last key, store above value. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM