将 json 文件中的数据提取到 python 文件中

Extracting data from a json file into a python file

我想做 Sobol (GSA) 分析。就此而言,我想从存储在 json 文件中的参数中提取数据到我的 python 文件(扩展名:ipynb)中。 我观看了一个视频和一个网站 (https://www.youtube.com/watch?v=9N6a-VLBa2I and https://yourblogcoach.com/how-to-extract-data-from-json-file-in-python/),但循环数据步骤不起作用。 我注意到他们使用列表,例如:

{"web": {
    "languages": [
        {
            "id": "1",
            "name": "PHP",
            "website": "https://www.php.net/"
        },
        {
            "id": "2",
            "name": "Python",
            "website": "https://www.python.org/"
        },
        {
            "id": "3",
            "name": "Java",
            "website": "https://www.java.com/en/"
        }
    ]
}

}

我的 json 文件看起来有点不同 - 我没有任何列表(带 [] 括号)。它就像一个对象字典:

{ "tech_water": { 
      "name": "Water",
      "value": 0.80,
      "description": "",
      "distribution": "normal",
      "arguments": {
        "mu": 0.20,
        "sigma": 0.02
      }
    },
  "tech_extruder": {
    "name": "Red ScaleUp",
    "value": 0.80,
    "description": "",
    "distribution": "normal",
    "arguments": {
      "mu": 0.40,
      "sigma": 0.02
     }
   }
 }

我做的是这样的:

import json

with open ('path', 'r') as json_file:
    json_load = json.load(json_file)
print(json.dumps(json_load, indent=2))

for parameter in json_load: #object to access the tech_water key
    print(parameter['name'])

然后我得到这个错误:

TypeError
Traceback (most recent call last)
c:\Users\karen...
      1 #Loop through data
      3 for parameter in json_load: #object to access the tech_water key
**----> 4     print(parameter['name'])
TypeError: string indices must be integers

有人知道我为什么或如何提取每个键的特定信息(例如名称、分布和来自“tech_water”和“tech_extruder”的参数吗?

下面是我要遵循的调试过程:

解释错误

您收到以下错误:TypeError: string indices must be integers 这意味着 parameter 是一个字符串。

如果您在错误之前打印 parameter,您会看到 parameter 包含 'tech_water'

我猜你期待什么

我猜你希望得到完整的字典

你的误会

您认为循环 dict 会得到 items,实际上它会得到 keys

可能的修复

循环值

for parameter in json_load.values(): 
    print(parameter['name'])

通过键访问值

for parameter in json_load:
    print(json_load[parameter]['name'])

如果你想查看tech_water的键和值,比如你只需要

for keys in json_load['tech_water']:
    print(keys, json_load['tech_water'][keys])

作为字典,您的 json 看起来就像您发布的格式化文件

{'tech_water': {'name': 'Water',
  'value': 0.8,
  'description': '',
  'distribution': 'normal',
  'arguments': {'mu': 0.2, 'sigma': 0.02}},
 'tech_extruder': {'name': 'Red ScaleUp',
  'value': 0.8,
  'description': '',
  'distribution': 'normal',
  'arguments': {'mu': 0.4, 'sigma': 0.02}}}