通过curl命令更新json文件

时间:2018-08-17 13:04:45

标签: python json curl

我正在尝试通过接受来自componentDidUpdate(prevProps) { if (this.props.id !== prevProps.id) { fetchData(this.props.id); } } 实用程序的数据来制作一个可以在json文件中进行写入和更新的应用。现在我的代码如下:

curl

import os import flask import Flask, url_for, json, request, jsonify database = "./meeting_rooms.json" @app.route('/book_room', methods = ['POST']) def api_book_room(): if request.headers['Content-Type'] == 'application/json': if os.stat(database).st_size == 0: with open(database, 'w') as f: data = request.get_json() json.dump (data, f, indent=4) return "OK\n", 200 else: with open(database,'r+') as f: data = json.load(f) data.update(request.get_json()) json.dump(data, f, indent=4) return "OK\n", 200 的用法:

curl

但是我只有

curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000/book_room -d '{"4":{"room":"602","date":"2 days ago","booked_by":"HR"}} '

考虑到我没有现实的json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)**. json file is empty. 经验,我在做什么错了?

1 个答案:

答案 0 :(得分:0)

一种在json解码时捕获错误的解决方案。它检查文件的存在和文件的错字。

import os
from flask import Flask, url_for, json, request, jsonify
from path import Path

app = Flask(__name__)

database = "./meeting_rooms.json"

@app.route('/book_room', methods = ['POST'])
def api_book_room():
  if request.headers['Content-Type'] == 'application/json':
    try:
      tmp = json.load(open(database, 'r'))
    except (ValueError, FileNotFoundError):
      # FileNotFoundError: raised if file don't exist
      # ValueError: raised if json is not able to decode
      tmp = {}


    for k, v in request.get_json().items():
      tmp[k] = v

    with open(database,'w') as f:
      json.dump(tmp, f, indent=4)

    return "OK\n", 200

  return "FAIL\n", 200

app.run(host='0.0.0.0', port=8080, debug=True)

编辑:更新密钥,而不是附加密钥。