Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse and Accessing inner elements in JSON

I'm having a nested JSON document and want to update elements in it. Below is the JSON file. Have validated this JSON via online formatting multiple times as well.

{
    "j1": [{
        "URL": "http://localhost/",
        "Data": "{\"dump\":[{values:[{time:1586826385724,val:5.12},{time:1587576460460,val:3.312}]}]}"
    }]
}

In this, I want to access 'values' and add element name: ABC and name: CBA in the subsequent entries.

{values:[{name:'ABC',time:1586826385724,val:5.12},
{name:'CBA',time:1587576460460,val:3.312}]}

Now with below code am getting a dictionary data but am not sure how to access the samples and its values through this dict.

Trying with dict object

import json
   with open("new1.json") as json_file:
   data = json.load(json_file)
   data['json1'][0]['DownloadData'][0:]

I tried using objectpath library for json element traversing but fetching empty result-set

#trying with objectpath lib
 import json
    import objectpath
    with open("new1.json") as json_file:
    data = json.load(json_file)
    jsonnn_tree = objectpath.Tree(data['json1'])    
    result_tuple = tuple(jsonnn_tree.execute('$..values'))

I do understand shouldn't ask for direct code, but not able to find anything relevant in this context on accessing nested JSON / dictionary. Being a novice, thought of seeking some guidance here.

like image 244
derek9988 Avatar asked Apr 24 '20 17:04

derek9988


People also ask

How do I iterate over a nested JSON object?

We can get json object in array with index(ie. index 0,1) or nested json object with string key. We can not iterate on nested json objects with string keys using jquery each() function. We need for (var key in obj) function to get json object, now you can apply option 1 formula to get object value.

How do you traverse through a JSON object in Python?

Use json. loads() With the Help of the for Loop to Iterate Through a JSON Object in Python. A built-in package, json , is provided by Python, which can be imported to work with JSON form data. In Python, JSON exists as a string or stored in a JSON object.

How do I get nested json data in Python?

Example of how to extract nested data Apartment number 1 and 2 have two residents. First you import the json module, this will allow you to transform the data into a python dictionary via the json. load() function. Next you open the data file and save the data to the variable data.

How do you flatten a json in Python?

There are many ways to flatten JSON. There is one recursive way and another by using the json-flatten library. Now we can flatten the dictionary array by a recursive approach which is quite easy to understand. The recursive approach is a bit slower than using the json-flatten library.


2 Answers

For me it looks that you have a nested JSON string here. And inner JSON isn't valid. So we have to fix it before parsing.

import json
with open("new1.json") as json_file:
   data = json.load(json_file)
innerstr = data["j1"][0]["Data"]
innerstr = innerstr.replace("values",'"walues"').replace("time",'"time"').replace("val",'"val"').replace("walues","values")
inner = json.loads(innerstr)
#then we can modify inner data as we want
inner["dump"][0]["values"][0]["name"] = "ABC"
inner["dump"][0]["values"][1]["name"] = "CBA"

And now we has innervariable like this

{'dump': [{'values': [{'name': 'ABC', 'time': 1586826385724, 'val': 5.12},
                      {'name': 'CBA', 'time': 1587576460460, 'val': 3.312}]}]}
like image 177
ex4 Avatar answered Oct 19 '22 17:10

ex4


It is a Relaxed JSON format. There is a A relaxed JSON parser for Python. Here is the example:

>>> import relaxedjson
>>> relaxedjson.parse('{moose: "goose"}')
{'moose': 'goose'}
like image 21
jumpman24 Avatar answered Oct 19 '22 15:10

jumpman24