如何使用Python在复杂的JSON对象中查找特定的JSON值

2024-09-29 02:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有一个复杂的JSON对象

[
    {
      "InvoiceNumberPrefix": "xx-",
      "InvoiceNumber": 33333,
      "OrderID": 905339301,
      "CustomerID": 44334555,
      "OrderDate": "2020-07-17T12:58:43",
      "OrderStatusID": 1,
      "LastUpdate": "2020-07-17T13:02:12",
      "UserID": "none",
      "SalesPerson": "none",
      "AlternateOrderID": "",
      "OrderType": "Repeat",
      "PaymentTokenID": 0,
      "BillingFirstName": "John",
      "BillingLastName": "Doe",
      "BillingCompany": "3dcart",
      "BillingAddress": "1234 Test St.",
      "BillingAddress2": "",
      "BillingCity": "Tamarac",
      "BillingState": "FL",
      "BillingZipCode": "33321",
      "BillingCountry": "US",
      "BillingPhoneNumber": "33444444",
      "BillingOnLinePayment": false,
      "BillingPaymentMethodID": "177"}
]

我试图在对象中找到特定的值。最初我只能指定关键点的位置,但问题是对象可能会很复杂,具有不同的关键点位置。有没有办法找到一个特定的值?例如,如果我试图查看JSON对象中是否包含“33333”,那么最好的方法是什么


Tags: 对象nonejson关键点xxuseridcustomeridinvoicenumber
2条回答

假设您已将JSON解析为Python中的变量data(字典列表),您可以执行以下操作:

target = '33333'
for i, d in enumerate(data, 1):
    for k, v in d.values():
        if v == target:
            print(f'found target {target} associated with key {k} on dictionary no {i}.'

如果您只想检查转换后的json dict的值中是否有变量,则可以执行以下操作:

import json

raw_json = """[{ "InvoiceNumberPrefix": "xx-", 
"InvoiceNumber": 33333, "OrderID": 905339301, 
"CustomerID": 44334555, "OrderDate": "2020-07- 
17T12:58:43", "OrderStatusID": 1, "LastUpdate": "2020-07- 
17T13:02:12", "UserID": "none", "SalesPerson": "none", 
"AlternateOrderID": "", "OrderType": "Repeat", 
"PaymentTokenID": 0, "BillingFirstName": "John", 
"BillingLastName": "Doe", "BillingCompany": "3dcart", 
"BillingAddress": "1234 Test St.", "BillingAddress2": "", 
"BillingCity": "Tamarac", "BillingState": "FL", 
"BillingZipCode": "33321", "BillingCountry": "US", 
"BillingPhoneNumber": "33444444", 
"BillingOnLinePayment": false, "BillingPaymentMethodID": 
"177"} ]"""

myjson = json.loads(raw_json)

def check4value(json_dict, value):
    if value in json_dict.values():
        return True
    else:
        return False

print(check4value(myjson[0], 33333))
#True

相关问题 更多 >