简体   繁体   中英

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM