简体   繁体   English

如何通过键从 json 中获取值作为 python 中的变量

[英]How to get value from json by key as a variable in python

I am trying for fetching some data from below json我正在尝试从 json 下面获取一些数据

[
    {
        "company": "XYZ",
        "companyAddress": "PQR",
        "staffDetails": [
            {
                "employeeCount": {
                    "jobLevel1": "9",
                    "jobLevel2": "10",
                    "jobLevel3": "11"
                },
                "otherStaff": {
                    "jobLevel1": "99",
                    "jobLevel2": "100"
                }
            }
        ]
    },
    
    {
        "company": "XXX",
        "companyAddress": "YYY",
        "staffDetails": [
            {
                "employeeCount": {
                    "jobLevel1": "9",
                    "jobLevel2": "10",
                    "jobLevel3": "11"
                },
                "otherStaff": {
                    "jobLevel1": "99",
                    "jobLevel2": "100"
                }
            }
        ]
    }
]

What data i want to fetch is configurable.我要获取的数据是可配置的。 eg below 2 details i want.例如,我想要以下 2 个详细信息。

config.properties配置属性

[details]
reqparameters=staffDetails.employeeCount.joblevel1 ,staffDetails.otherStaff.joblevel2

myPython code is like below- myPython 代码如下 -

   import configparser
    import json
    config=configparser.RawConfigParser()
    config.read('config.properties')
    parameters=config.get('details','reqparameters')
    splitedValue=responseDetails.split(",")
    resp='''    [
            {
                "company": "XYZ",
                "companyAddress": "PQR",
                "staffDetails": [
                    {
                        "employeeCount": {
                            "jobLevel1": "9",
                            "jobLevel2": "10",
                            "jobLevel3": "11"
                        },
                        "otherStaff": {
                            "jobLevel1": "99",
                            "jobLevel2": "100"
                        }
                    }
                ]
            },
            
            {
                "company": "XXX",
                "companyAddress": "YYY",
                "staffDetails": [
                    {
                        "employeeCount": {
                            "jobLevel1": "9",
                            "jobLevel2": "10",
                            "jobLevel3": "11"
                        },
                        "otherStaff": {
                            "jobLevel1": "99",
                            "jobLevel2": "100"
                        }
                    }
                ]
            }
        ]'''
    #x = json.loads(resp, object_hook=lambda d: SimpleNamespace(**d))
    x = json.loads(resp)
    
    for property in splitedValue:
     for jNode in x:
       print(jNode[property])
       print(jNode.property)

tried both the ways print(jNode[property]) & print(jNode.property) along with x = json.loads(resp, object_hook=lambda d: SimpleNamespace(**d)) but it's not working.尝试了两种方式 print(jNode[property]) & print(jNode.property) 以及 x = json.loads(resp, object_hook=lambda d: SimpleNamespace(**d)) 但它不起作用。 As my input is configurable i can't harcode that with jNode so need it with dynamically using variable property which i am reading from properties file由于我的输入是可配置的,我无法使用 jNode 对其进行硬编码,因此需要动态使用我从属性文件中读取的变量属性

This is not how JSON handling works in Python to access the sections you need would use:这不是 JSON 处理在 Python 中的工作方式,以访问您需要使用的部分:

jNode['staffDetails'][0]['employeeCount']['jobLevel1']

There is an issue in your data the config file says joblevel1 but the key in the json is jobLevel1 (capital L) The other issue you are going to have here is that staffDetails is a list so do you know that it will always be one element?您的数据中有一个问题,配置文件joblevel1 ,但 json 中的键是jobLevel1 (大写 L)您将在这里遇到的另一个问题是staffDetails是一个列表,所以您知道它永远是一个元素? or could it be more?还是可以更多?

Doing this directly in Python would be messy eg直接在 Python 中执行此操作会很麻烦,例如

In [564]:
    ...: for config in splitedValue:
    ...:     for company in x:
    ...:         data = company
    ...:         for node in config.split('.'):
    ...:             if isinstance(data, type(list)):
    ...:                 data = data[0]
    ...:             data = data[node]
    ...:         print(f"company: {company['company']} {config}: {data}")
    ...:
company: XYZ staffDetails.employeeCount.jobLevel1: 9
company: XXX staffDetails.employeeCount.jobLevel1: 9
company: XYZ staffDetails.otherStaff.jobLevel2: 100
company: XXX staffDetails.otherStaff.jobLevel2: 100

Personally I would look at making changes to the JSON and the config file to make them work better together我个人会考虑对 JSON 和配置文件进行更改,以使它们更好地协同工作

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

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