阅读Json obect时读错误

时间:2017-07-12 13:00:54

标签: python json

我有一个像这样的json对象列表:

json_data = [{"Timestamp":"4/1/2017 7:00","Maximum Demand (KVA)":123,"Consumption (KVAh)":271,"Power Factor":0.86},{"Timestamp":"4/1/2017 8:00","Maximum Demand (KVA)":119,"Consumption (KVAh)":260,"Power Factor":0.85},{"Timestamp":"4/1/2017 9:00","Maximum Demand (KVA)":125,"Consumption (KVAh)":264,"Power Factor":0.9}]

我尝试了json.loads,但是它引发了一个错误:

data = json.loads(json_data)

也尝试了这个:

with open(json_data) as data_file:
        data = json.load(data_file)

错误:

  

TypeError:预期的字符串或Unicode

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

jsons.loads将字符串化的json转换为python对象。 json.dumps将python对象转换为包含相应json的字符串。在这里你应该使用json.dumps。 数据= json.dumps(json_data)

答案 1 :(得分:0)

我希望这可以帮助你...

import  json
json_data = [{"Timestamp":"4/1/2017 7:00","Maximum Demand (KVA)":123,"Consumption (KVAh)":271,"Power Factor":0.86},
             {"Timestamp":"4/1/2017 8:00","Maximum Demand (KVA)":119,"Consumption (KVAh)":260,"Power Factor":0.85},
             {"Timestamp":"4/1/2017 9:00","Maximum Demand (KVA)":125,"Consumption (KVAh)":264,"Power Factor":0.9}]


data = json.dumps(json_data)
print data

输出:

[{"Power Factor": 0.86, "Timestamp": "4/1/2017 7:00", "Consumption (KVAh)": 271, "Maximum Demand (KVA)": 123}, {"Power Factor": 0.85, "Timestamp": "4/1/2017 8:00", "Consumption (KVAh)": 260, "Maximum Demand (KVA)": 119}, {"Power Factor": 0.9, "Timestamp": "4/1/2017 9:00", "Consumption (KVAh)": 264, "Maximum Demand (KVA)": 125}]