如何在Python中使用JSON



我的JSON文件有问题,我用web服务器python填充JSON,但我试图在JSON文件中放入方括号([]),并在每个对象的末尾放入逗号(,)。括号开得很好,逗号也开得很好,但右括号不想打开。如果有人知道如何帮助我。

from asyncio import tasks
import json
import os
from flask import Flask, render_template, jsonify, url_for, request
from flask_restful import Api, Resource, reqparse
#from jinja2 import Markup
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('task')
class TodoResource(Resource):
def get(self):
return {'tasks': tasks}
def post(self):
args = parser.parse_args()
task = {'task': args['task']}
tasks.append(task)
return task, 201
api.add_resource(TodoResource, '/tasks')
@app.route('/', methods=["GET", "POST"])
def home():
if request.method == 'POST':
data = request.form
with open("./data.json", "a") as f:
if f.tell() == 0:
f.write("[n")
else:
f.write(",n")
json.dump(data, f)
return render_template('home.html')
@app.route('/end', methods=["GET", "POST"])
def end():
with open("./data.json", "r+") as f:
data = json.load(f)
f.seek(0)
f.write("[")
for i, obj in enumerate(data):
if i != 0:
f.write(",")
json.dump(obj, f)
f.write("n]")
f.flush()
os.fsync(f.fileno())
return render_template('home.html')
@app.route('/data')
def get_data():
with open('data.json') as f:
data = json.load(f)
return jsonify(data)
if __name__ == '__main__':
#app.run(debug=True)
app.run(host='0.0.0.0', port=5000, debug=True)

这是我的Json文件:

[
{"alley": "B", "row": "C", "height": "0"},
{"alley": "A", "row": "A", "height": "0"},
{"alley": "D", "row": "B", "height": "3"},
{"alley": "B", "row": "C", "height": "3"},
{"alley": "", "row": "", "height": ""},
{"alley": "B", "row": "A", "height": "1"},
{"alley": "B", "row": "A", "height": "1"},
{"alley": "C", "row": "C", "height": "0"}

就像你看到的,我有左括号和逗号但是我没有结束括号

我试过了,但是没有成功:

@app.route('/end', methods=["GET", "POST"])
def end():
with open("./data.json", "r+") as f:
data = json.load(f)
f.seek(0)
f.write("[")
for i, obj in enumerate(data):
if i != 0:
f.write(",")
json.dump(obj, f)
f.write("n]")
f.flush()
os.fsync(f.fileno())

最后一行,我试着强行写

我看到两个端点,一个用于/,一个用于/end/的端点从不写入右括号:

@app.route('/', methods=["GET", "POST"])
def home():
if request.method == 'POST':
data = request.form
with open("./data.json", "a") as f:
if f.tell() == 0:
f.write("[n")
else:
f.write(",n")
json.dump(data, f)
# f.write("n]") # <<< This line is missing.
return render_template('home.html')

也许你看到的结果来自第一个端点?在这种情况下,添加上面注释掉的行。

相关内容

  • 没有找到相关文章

最新更新