Home > Backend Development > Python Tutorial > How to Access Nested JSON Data: Extracting the \'content\' Field?

How to Access Nested JSON Data: Extracting the \'content\' Field?

DDD
Release: 2024-11-28 19:48:17
Original
121 people have browsed it

How to Access Nested JSON Data: Extracting the

Accessing Nested Data in Complex JSON

How do we access the "content" field from the following JSON data?

{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1515580011",
    "video_info": [
      {
          "announcement": "{\"announcement_id\":\"6\",\"name\":\"INS\u8d26\u53f7\",\"icon\":\"http:\\/\\/liveme.cms.ksmobile.net\\/live\\/announcement\\/2017-08-18_19:44:54\\/ins.png\",\"icon_new\":\"http:\\/\\/liveme.cms.ksmobile.net\\/live\\/announcement\\/2017-10-20_22:24:38\\/4.png\",\"videoid\":\"15154610218328614178\",\"content\":\"FOLLOW ME PLEASE\",\"x_coordinate\":\"0.22\",\"y_coordinate\":\"0.23\"}",
          "announcement_shop": ""
      }
    ]
  }
}
Copy after login

Solution

To extract the desired "content" value, we must first load the JSON data into a Python dict. Then, we traverse the nested data structure as follows:

  1. Access the "data" key to get the inner dictionary.
  2. Access the "video_info" key in the inner dictionary, which contains a list of dictionaries.
  3. Access the first dictionary in the "video_info" list using its index (in this case, 0).
  4. The announcement string, which is stored in the "announcement" key, is itself a JSON string. Convert it into a dict using json.loads.
  5. Finally, access the "content" key in the parsed announcement dictionary.

Python code:

import json

raw_data = {
  # JSON data pasted here
}

data = raw_data['data']['video_info'][0]

# Convert the announcement string to a dict
announcement_data = json.loads(data['announcement'])

# Retrieve the desired content
content = announcement_data['content']

print(content)  # Output: 'FOLLOW ME PLEASE'
Copy after login

By following this approach, we can navigate complex JSON structures and extract the desired data efficiently.

The above is the detailed content of How to Access Nested JSON Data: Extracting the \'content\' Field?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template