首页 > 解决方案 > 读取 .json 的第二个条目

问题描述

我正在尝试读取 .json 文件中数组列表的密度条目。他从一开始就是文件的一小部分:

["time_tag","density","speed","temperature"],["2019-04-14 18:20:00.000","4.88","317.9","11495"],["2019-04-14 18:21:00.000","4.89","318.4","11111"]

这是我到目前为止的代码:

with open('plasma.json', 'r') as myfile:
  data = myfile.read()

obj = json.loads(data)

print(str(obj['density']))

它应该打印密度列下的所有内容,但我收到一条错误消息,提示无法打开文件

标签: python

解决方案


您确定您的数据是有效的 json 而不是 csv 吗?
由于上面提供的数据片段与 csv 文件而不是 json 相匹配。

您将能够通过以下方式读取densitycsv 的密钥:

import csv

input_file = csv.DictReader(open("plasma.csv"))
for row in input_file:
    print(row['density'])

数据格式为 csv

["time_tag","density","speed","temperature"]
["2019-04-14 18:20:00.000","4.88","317.9","11495"]
["2019-04-14 18:21:00.000","4.89","318.4","11111"]

结果

4.88
4.89

推荐阅读