![](/img/trans.png)
[英]Parsing a complex JSON object with Python: search a specific key/value pair
[英]How to find specific JSON value in complex JSON object with Python
您好我有一个复杂的 JSON object
[
{
"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"}
]
我正在尝试在 object 中找到特定值。 最初我只能指定密钥的位置,但问题是 object 可能会因不同的密钥位置而变得复杂。 有没有办法找到一个特定的值? 例如,如果我想查看 JSON object 中是否有“33333”,那么 go 的最佳方法是什么?
假设您已将 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 字典的值中,那么您可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.