【问题标题】:Access json data from a file and use it in python script从文件中访问 json 数据并在 python 脚本中使用它
【发布时间】:2017-08-03 23:26:00
【问题描述】:

我有一个 json 文件,其中包含:

[{
    "id": "a1",
    "num": "1"
}, {
    "id": "a2",
    "num": "3"
}, {
    "id": "a3",
     "num": "2"
}]

我正在使用 plotly 来绘制它, 这是我的代码: 将 plotly.plotly 导入为 py 导入 plotly.graph_objs 导入json 从 pprint 导入 pprint

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

    pprint(data)


  data = [go.Bar(
        x=['a1', 'a2', 'a3'],
        y=[1,3,2]
        )]

  py.iplot(data, filename='basic-bar')

代替

x = ['a1', 'a2','a3']
y=[1,3,2]

我尝试通过以下方式访问它:

for key.value in data.items():
    print(key,value)

抛出错误: 回溯(最近一次通话最后): 文件“plotlyExample.py”,第 11 行,在 对于 data.items() 中的 key.value: AttributeError:“列表”对象没有属性“项目”

我想到的地方:

a1,a2,a3

将是键和 1,3,2 会是值吗?

我想从 json 文件中读取它。我可以看到数据有输出,但不知道我将如何使用它。

任何指针将不胜感激。

【问题讨论】:

  • json.load('filename') 就够了,不用打开什么的

标签: python json plotly


【解决方案1】:

使用list comprehension 遍历数据的字典列表并返回一个新列表。

data = [go.Bar(
    x=[x['id'] for x in data],
    y=[int(x['num']) for x in data]
)]

【讨论】:

    【解决方案2】:

    在创建图表之前,您必须将 json 解析为 x 和 y 列表

    data = json.load(data_file)
    
    # will yield x and y arrays
    x = [i['id'] for i in data]
    y = [int(i['num']) for i in data]
    

    由于您的 num 键的值是字符串,因此您应该在绘图之前将它们转换为整数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      相关资源
      最近更新 更多