avorter avorter - 6 months ago 37
Python Question

Parsing nested json payload python

I am trying to get only value A from from this nested json payload.

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 ...]

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)

Answer

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. Since lists in Python are zero-indexed (they start from zero) you'll use [0] to extract the first element:

data["bod"]["id"][0]["value"]