[英]Parsing nested json payload python
I am trying to get only value A from from this nested json payload.我试图从这个嵌套的 json 负载中只获取值 A。
My function:我的功能:
import requests
import json
def payloaded():
from urllib.request import urlopen
with urlopen("www.example.com/payload.json") as r:
data = json.loads(r.read().decode(r.headers.get_content_charset("utf-8")))
text = (data["bod"]["id"])
print(text)
The payload:有效载荷:
bod: {
id: [
{
value: "A",
summary: "B",
format: "C"
}
]
},
Currently it is returning everything within the brackets [... value ... summary ... format ...]目前它正在返回括号内的所有内容 [... value ... summary ... 格式 ...]
Solution found:找到的解决方法:
def payloaded():
from urllib.request import urlopen
with urlopen("www.example.com/payload.json") as r:
data = json.loads(r.read().decode(r.headers.get_content_charset("utf-8")))
text = (data["bod"]["id"][0]["value"])
print(text)
Since the id
value is a list (even though it just contains a single value), you'll need to go inside it with a list indexer.由于
id
值是一个列表(即使它只包含一个值),您需要使用列表索引器进入它。 Since lists in Python are zero-indexed (they start from zero) you'll use [0]
to extract the first element:由于 Python 中的列表是零索引的(它们从零开始),因此您将使用
[0]
来提取第一个元素:
data["bod"]["id"][0]["value"]
This works:这有效:
def payloaded():
from urllib.request import urlopen
with urlopen("www.example.com/payload.json") as r:
data = json.loads(r.read().decode(r.headers.get_content_charset("utf-8")))
text = (data["bod"]["id"][0]["value"])
print(text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.