如何使用Python在复杂的JSON对象中查找特定的JSON值
你好,我有一个复杂的JSON对象如何使用Python在复杂的JSON对象中查找特定的JSON值,python,json,Python,Json,你好,我有一个复杂的JSON对象 [ { "InvoiceNumberPrefix": "xx-", "InvoiceNumber": 33333, "OrderID": 905339301, "CustomerID": 44334555, "OrderDate": "2020-07-17T12:58
[
{
"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”,那么最好的方法是什么?假设您已将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
在Python中,JSON只是一个字符串,除非将其转换为Python数据类型。实现这一点的典型方法是使用json库中的方法json.reads()。在您的例子中,您是否将对象转换为Python列表,或者它只是一个JSON字符串?(从您呈现它的方式来看,该对象似乎会转换为字典列表)。很抱歉,在上面的注释中,我指的是json.loads(),而不是json.reads()。