繁体   English   中英

如何使用 python 从 json 中提取数据

[英]how do you extract data from json using python

我有这个 json 文件:

{
  "entityId": "12345",
  "displayName": "hostabc",
  "toRelationships": {
    "isProcessOf": [
      {
        "id": "proce123D00BB86",
        "type": "PROCESS_GROUP_INSTANCE"
      },
      {
        "id": "proc678DD0DBA4",
        "type": "PROCESS_GROUP_INSTANCE"
      },
      {
        "id": "proc978DD0DBA4",
        "type": "PROCESS_GROUP_INSTANCE"
      }
      
    ]
  }
}

我需要提取 isProcessOf 下的 id 字段并构建一个数据列表。

我是 python 的新手,我该怎么做?

看起来列表理解可以完成这项工作。 您通过其键访问字典值,因此,由于您想访问'isProcessOf'键下的列表中的字典的'id' ,而后者又位于'toRelationships'键下,您可以这样做:

out = [d['id'] for d in dct['toRelationships']['isProcessOf']]

Output:

['proce123D00BB86', 'proc678DD0DBA4', 'proc978DD0DBA4']

我会在 python 中使用 json package 然后使用列表理解读取数据:

import json
file_dir = "<YOUR_FILE_DIR>"
with open(file_dir ) as f:
    data = json.load(f)
id_list = [process['id'] for process in data['toRelationships']['isProcessOf']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM