Home > Backend Development > Python Tutorial > How to Extract a String from a Nested JSON Document Within Another String?

How to Extract a String from a Nested JSON Document Within Another String?

Patricia Arquette
Release: 2024-12-03 03:32:18
Original
637 people have browsed it

How to Extract a String from a Nested JSON Document Within Another String?

Accessing Nested Data When One String Contains Another JSON Document

You have complex JSON data with nested elements, including a JSON document embedded within a string. Your goal is to extract a specific string, "FOLLOW ME PLEASE", from this nested structure.

{
  "status": "200",
  "msg": "",
  "data": {
    "time": "1515580011",
    "video_info": [
      {
          "announcement": "{\"...announcement_id\":\"6\",\"name\":\"INS\u8d26\u53f7\",\"content\":\"FOLLOW ME PLEASE\"...}",
          "announcement_shop": ""
      }
    ]
  }
}
Copy after login

Solution:

To access the nested data and extract the desired string, you can use the following steps:

  1. Access the "data" dictionary: data = json_data['data']
  2. Access the "video_info" list: video_info = data['video_info']
  3. Access the first element (assuming it contains the desired information) of the "video_info" list: video_info_element = video_info[0]
  4. Load the "announcement" string as a JSON document using json.loads(): announcement_json = json.loads(video_info_element['announcement'])
  5. Access the "content" key from the loaded JSON document: content = announcement_json['content']

By following these steps, you can extract the desired string, "FOLLOW ME PLEASE," from the nested JSON structure.

import json

raw_replay_data = {...}

# Access the desired information
json_data = json.loads(raw_replay_data)
data = json_data['data']
video_info = data['video_info']
video_info_element = video_info[0]
announcement_json = json.loads(video_info_element['announcement'])
content = announcement_json['content']

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

The above is the detailed content of How to Extract a String from a Nested JSON Document Within Another String?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template