[英]In Python parse a generic JSON structure looking for specific values
我正在嘗試解析JSON結構並尋找特定的值。
這里是一個可能的數據解析示例:
{
"objects": [
{
"from": 44,
"my_ref": "http://192.168.10.1/index.php",
"allow": "no",
"to": 10
},
{
"from": 20,
"my_ref": "http://192.168.10.2/index.php",
"allow": "mandatory",
"to": 0
}
],
"comment": "My PHP",
"identifiable_with_user": true,
"key": 10,
"link": [
{
"href": "http://192.168.10.1/index.php",
"method": "GET",
"rel": "self",
"type": "website"
},
{
"href": "http://192.168.10.5/identifiable.php",
"method": "GET",
"rel": "account_info"
}
],
"name": "Accounts",
"read_only": true,
"system": true,
"system_key": 20,
"tls_match_ref": "http://192.168.10.5/accounts.php"
}
我需要在通用JSON結構中提取由鍵* ref標識的所有值(例如my_ref,href等)。 我只需要提取URL,然后執行一些操作:
for entities in JSON_structure
URL= "take the URL corresponding to the ref key"
so something with the URL
我嘗試使用.items()過濾“ http://”字符串,但沒有用
URL = {k:v for (k,v) in element_detail.items() if "http://" in k or v}
您應該解析數據,然后在其中查找帶有ref的鍵。
達到目的:
import json
def parse(root):
for k,v in root.items():
if isinstance(v, list):
for e in v:
parse(e)
else:
if 'ref' in k:
print(k + ':' + v)
json_data = '{\
"objects": [\
{ "from": 44, "my_ref": "http://192.168.10.1/index.php", "allow": "no", "to": 10 },\
{ "from": 20, "my_ref": "http://192.168.10.2/index.php", "allow": "mandatory", "to": 0 }\
],\
"comment": "My PHP",\
"identifiable_with_user": true,\
"key": 10,\
"link": [\
{ "href": "http://192.168.10.1/index.php", "method": "GET", "rel": "self", "type": "website" },\
{ "href": "http://192.168.10.5/identifiable.php", "method": "GET", "rel": "account_info" }\
],\
"name": "Accounts",\
"read_only": true,\
"system": true,\
"system_key": 20,\
"tls_match_ref": "http://192.168.10.5/accounts.php"\
}'
data = json.loads(json_data)
parse(data)
輸出:
href:http://192.168.10.1/index.php
href:http://192.168.10.5/identifiable.php
my_ref:http://192.168.10.1/index.php
my_ref:http://192.168.10.2/index.php
tls_match_ref:http://192.168.10.5/accounts.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.