如何使用Python Flask读取JSON字符串及用Python模块筛选webserver1
问题1:如何使用Python Flask读取JSON字符串
场景1:接收客户端POST请求中的JSON
Flask的request.get_json()方法可直接解析请求体中的JSON数据,要求请求头包含Content-Type: application/json。
from flask import Flask, request app = Flask(__name__) @app.route('/receive-json', methods=['POST']) def receive_json(): json_data = request.get_json() # 按需处理数据,示例返回接收确认 return {'status': 'success', 'received_data': json_data} if __name__ == '__main__': app.run(debug=True)
场景2:读取本地JSON文件并返回
结合Python标准库json读取本地JSON文件,再通过Flask路由返回数据:
from flask import Flask import json app = Flask(__name__) @app.route('/get-local-json', methods=['GET']) def get_local_json(): with open('your_file.json', 'r', encoding='utf-8') as f: json_content = json.load(f) return json_content if __name__ == '__main__': app.run(debug=True)
问题2:读取并筛选包含“webserver1”的JSON数据
你提供的JSON存在语法错误(键值对间缺少逗号、Instant字段值为字符串格式的数组),先修正为合法JSON后再处理,分两种常见情况:
情况1:Instant为字符串格式的数组
修正后的JSON示例:
{ "Title": "Nginx Service", "Instant": "[{\"Hostname\":\"webserver1\"}]" }
读取并筛选的代码:
import json # 读取JSON文件 with open('data.json', 'r', encoding='utf-8') as f: raw_data = json.load(f) # 解析Instant字段的字符串为数组 instant_entries = json.loads(raw_data['Instant']) # 筛选Hostname为webserver1的条目 filtered = [entry for entry in instant_entries if entry.get('Hostname') == 'webserver1'] print(filtered) # 输出: [{'Hostname': 'webserver1'}]
情况2:Instant本身为JSON数组(更规范的写法)
修正后的JSON示例:
{ "Title": "Nginx Service", "Instant": [{"Hostname": "webserver1"}] }
筛选代码可简化为:
import json with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f) filtered = [entry for entry in data['Instant'] if entry.get('Hostname') == 'webserver1'] print(filtered)
内容的提问来源于stack exchange,提问作者user2153058
相关产品推荐
相关产品推荐

