用Python查询JSON

时间:2017-06-01 15:00:51

标签: python json pandas

我用json.load解析了JSON。 现在我想使用类似SQL的命令查询JSON dict。 Python中有这样的东西吗?我尝试使用Pynq https://github.com/heynemann/pynq,但是效果不好而且我也调查过Pandas,但不确定这是否是我需要的。

1 个答案:

答案 0 :(得分:0)

这是一个简单的pandas示例,使用Python 2.7来帮助您入门......

import json
import pandas as pd

jsonData = '[ {"name": "Frank", "age": 39}, {"name": "Mike", "age": 
18}, {"name": "Wendy", "age": 45} ]'

# using json.loads because I'm working with a string for example

d = json.loads(jsonData)

# convert to pandas dataframe

dframe = pd.DataFrame(d)

# Some example queries

# calculate mean age
mean_age = dframe['age'].mean()

# output - mean_age
# 34.0

# select under 40 participants
young = dframe.loc[dframe['age']<40]

# output - young
#   age   name
#0   39  Frank
#1   18   Mike


# select Wendy from data
wendy = dframe.loc[dframe['name']=='Wendy']

# output - wendy
#    age   name
# 2   45  Wendy