python - 如何检查文本文件是否包含 URL 或 JSON?
问题描述
我编写了获取文本文件的代码(FLASK 应用程序)并检查它是否包含 URL 或 JSON。如果是 URL,则获取它并将其作为 JSON 显示给用户,否则,如果它是 JSON,则仅将其原样显示给用户。我想知道我的代码是否是这些东西的正确表示。文本文件可以是以下形式(JSON 或 URL):
text.txt > '{"name":"John", "age":30, "car":null}'
text.txt > http://example.com/contents/example.json
from flask import Flask, jsonify, abort, make_response
from flask_restful import Resource, Api
import requests, json
import urllib.request as request
app = Flask(__name__)
api = Api(app)
@app.route('path', methods=["POST"])
@app.error
class test(Resource):
def do_test(self):
with open("test.txt", "r") as md:
text = md.read()
for i in text.readlines():
URL = requests.get(i)
if URL.ok:
data = json.loads(URL.read())
return jsonify(data)
else:
abort(make_response(jsonify(404, message = "No URL found"),400))
elif text.read(1) in '{[':
data = json.load(text)
return jsonify(data)
api.add_resource(test, 'path')
if __name__ == '__main__':
app.run(debug=True)
解决方案
您可以使用 try/except 块。就像是
try:
data = json.load(text)
except JSONDecodeError:
url = text
您需要对其进行测试并添加适当的异常,JSONDecodeError 只是一个示例,但您明白了。
推荐阅读
- python - 替代在 wxPython Grid 中有一个表
- python - 根据参数过滤
- import - odoo v14:从 xlsx 或 eml 导入票证及其消息
- javascript - expo 错误“元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。”
- sql - {SAS} 将 SQL 合并转换为 HASH 合并
- python - 如何运行 Pylint 来检查项目中整个文件夹的分数
- python-3.x - Walmart API-现有类型错误问题-批量项目设置(多个)
- shell - 如何 grep 仅当前目录中的今天的文件?
- angular - 有没有办法在角度 cdk-virtual-scroll 中禁用滚动?
- architecture - 软件工程