Home > Back-end >  how to use variables to read in nested json
how to use variables to read in nested json

Time:06-22

I want to read in a nested json like

"Experiment"{
        "rats"{
            "animal":[1,2,3,4]
              }
        "dogs"{
            "animal":[1,2,3,4]
              }
            } 

(I hope I set all the brackets correctly)

Now I want to make it variable to read in Dogs or rats (do not worry, I am not actually experimenting on animals :-) )

So instead of

conf=pd.read_json(filepath)
animal=conf[Experiment][dogs][1]

I would like to use

conf=pd.read_json(filepath)
a="dogs"
b="rats"
animal=conf[Experiment]a[1]

Can someone hint how to do this? Thanks

CodePudding user response:

You essentially have the answer within your question, as long as you clean up the syntax. If you change your json to this:

{
    "Experiment": {
        "dogs": {
            "animal": [ 1, 2, 3, 4 ]
        },
        "rats": {
            "animal": [ 1, 2, 3, 4 ]
        }
    }
}

(Note the comma after "dogs", surrouding {} and : to separate keys and values) You can do it the first way with:

import pandas as pd

conf = pd.read_json("animals.json")
animal = conf["Experiment"]["dogs"]["animal"]

Or the way you wanted with:

import pandas as pd

a = "dogs"
conf = pd.read_json("animals.json")
animal = conf["Experiment"][a]["animal"]

I assumed what you're trying to grab is the array [1,2,3,4], but if you want "animal": [1,2,3,4], just leave off ["animal"] from above. Your question lacks quotes around the keys, so that was likely your issue. You can easily set a variable to be the string of the key you're looking for ("dog") and use that. You also attempted to index dogs with [1], but dogs isn't an array, so perhaps you meant to put [] around "animal": [ 1, 2, 3, 4 ] instead of {}?

Also, you don't necessarily need to use pandas (unless you're doing a lot more other than mentioned here). You can also do it like so:

import json

a = "dogs"
f = open("animals.json")
conf = json.load(f)
animal = conf["Experiment"][a]["animal"]
  • Related