How to Extract Specific Fields from JSON Files in Python: 4 Practical Methods
This tutorial walks through four effective techniques—including regular expressions and three jsonpath approaches—to extract the follower and ddate fields from a JSON file using Python, complete with code snippets and example outputs.
Introduction
In a WeChat group a fan asked how to extract the follower and ddate fields from a JSON file.
Approach
Four practical solutions are presented: regular expressions, three variations of jsonpath, and direct JSON loading.
1. Regular expression
import re
import json
file = open('漫画.txt', 'r', encoding='utf-8')
content = file.readline()
ddate_result1 = re.findall('"ddate":"(\d+-\d+-\d+)"', content)
ddate_result2 = re.findall('"ddate":"(.*?)"', content)
follower_result1 = re.findall('"follower":(\d+),"', content)
print(ddate_result1)
print(ddate_result2)
print(follower_result1)The script prints the extracted dates and follower counts.
2. jsonpath method 1
from jsonpath import jsonpath
import json
with open("漫画.txt", encoding="utf-8") as file:
file_json = json.loads(file.readline())
follower = jsonpath(file_json, "$..follower")
ddate = jsonpath(file_json, "$..ddate")
print(follower)
print(ddate)The $.. syntax works like XPath //, selecting all descendant nodes.
3. jsonpath method 2
import json
import jsonpath
file = open('漫画.txt', 'r', encoding='utf-8')
obj = json.loads(file.readline())
follower = jsonpath.jsonpath(obj, '$..follower')
ddate = jsonpath.jsonpath(obj, '$..ddate')
print(follower)
print(ddate)4. jsonpath method 3
import json
import jsonpath
with open("罗翔.txt", 'r', encoding="UTF-8") as fr:
file_json = eval(fr.read().replace('
\u200b', ''))
follower = jsonpath.jsonpath(file_json, '$..follower')
ddate = jsonpath.jsonpath(file_json, '$..ddate')
print(follower)
print(ddate)Conclusion
The article consolidates four workable ways to pull specific fields from JSON files, recommending jsonpath as a convenient library for future data‑extraction tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
