如何去除JSON中的count、next等属性,仅保留results数组数据?
提取JSON中的results数组方法
以下是几种不同场景下的实现方式:
Python 环境
直接利用Python内置的json模块解析数据,提取目标字段即可:
import json # 原始JSON数据(可替换为从文件/接口读取的内容) raw_json = '''{"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]}''' # 解析JSON字符串 parsed_data = json.loads(raw_json) # 提取results数组 results_array = parsed_data["results"] # 输出格式化后的JSON print(json.dumps(results_array, indent=2))
命令行(jq工具)
如果是在终端处理JSON文件或字符串,使用jq工具可以快速提取字段:
# 直接处理字符串 echo '{"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]}' | jq '.results' # 处理文件的话,假设文件名为data.json jq '.results' data.json
JavaScript/Node.js 环境
在前端或Node.js中,用原生JSON API解析提取:
// 原始JSON数据 const rawJson = '{"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]}'; // 解析JSON const data = JSON.parse(rawJson); // 获取results数组 const results = data.results; // 输出结果 console.log(JSON.stringify(results, null, 2));
内容的提问来源于stack exchange,提问作者M GUDA
相关产品推荐
相关产品推荐

