简体   繁体   中英

Getting values from json array using an array of object and keys in Python

I'm a Python newbie and I'm trying to write a script to extract json keys by passing the keys dinamically, reading them from a csv. First of all this is my first post and I'm sorry if my questions are banals and if the code is incomplete but it's just a pseudo code to understand the problem (I hope not to complicate it...)

The following partial code retrieves the values from three key (group, user and id or username) but I'd like to load the objects and key from a csv to make them dinamicals.

Input json

{
"fullname": "The Full Name",
"group": {
            "user": {
                        "id": 1,
                        "username": "John Doe"
                    },
            "location": {
                        "x": "1234567",
                        "y": "9876543"
                        }
        },
"color": {
            "code": "ffffff",
            "type" : "plastic"
        }
}

Python code...

...
url = urlopen(jsonFile)
data = json.loads(url.read())
id = (data["group"]["user"]["id"])
username = (data["group"]["user"]["username"])
...

File.csv loaded into an array. Each line contains one or more keys.

fullname;
group,user,id;
group,user,username;
group,location,x;
group,location,y;
color,code;

The questions are: can I use a variable containing the object or key to be extract? And how can I specify how many keys there are in the keys array to put them into the data([ ][ ]...) using only one line?

Something like this pseudo code:

...
url = urlopen(jsonFile)
data = json.loads(url.read())
...
keys = line.split(',')
...
# using keys[] to identify the objects and keys
value = (data[keys[0]][keys[1]][keys[2]])
...

But the line value = (data[keys[0]][keys[1]][keys[2]]) should have the exact number of the keys per line read from the csv. Or I must to make some "if" lines like these?:

...
if len(keys) == 3:
   value = (data[keys[0]][keys[1]][keys[2]])
if len(keys) == 2:
   value = (data[keys[0]][keys[1]])
...

Many thanks!

I'm not sure I completely understand your question, but I would suggest you to try and play with pandas . It might be as easy as this:

import pandas as pd

df = pd.read_json(<yourJsonFile>, orient='columns')
name = df.fullname[0]
group_user = df.group.user 
group_location = df.group.location
color_type = df.color.type 
color_code = df.color.code

(Where group_user and group_location will be python dictionaries ).

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