附加到现有的json文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了附加到现有的json文件相关的知识,希望对你有一定的参考价值。
我试图仅在特定的地方将现有的json文件追加到json中,这些额外的问题会被询问,其余的保持不变。我已经通过解析json开发了一种逻辑,但修改后似乎无法正常工作。这是我的代码:-
import os
from flask import Flask, flash, request, redirect, url_for, session
from flask import send_from_directory, abort
from werkzeug.utils import secure_filename
from flask_cors import CORS, cross_origin
import logging
import json
import flask_cors
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('HELLO WORLD')
target = ""
tag_name = ""
global data
UPLOAD_FOLDER = 'H:/JS'
UPLOAD_FILE = 'H:/JS/exp/api'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['UPLOAD_FILE'] = UPLOAD_FILE
questionsP1 = []
questionsP2 = []
questionsP3 = []
questionsP4 = []
questionTag = {}
@app.route('/upload', methods=['POST'])
def fileUpload():
global target
target=os.path.join(UPLOAD_FOLDER,'uploads')
if not os.path.isdir(target):
os.mkdir(target)
logger.info("Welcome To Upload`")
file = request.files['file']
filename = secure_filename(file.filename)
logger.info(filename)
destination="/".join([target, filename])
logger.info(destination)
logger.info(os.path)
logger.info(target)
file.save(destination)
with open('H:/JS/uploads/' +
file.filename) as f:
# data1 = f.read()
global data
data = json.load(f)
# logger.info(data1)
global tag_name
tag_name = data['intents'][0]['tech']
if(os.path.exists(target + "/" + tag_name + ".json")):
return "File already exists"
else:
try:
os.rename(
r'H:/JS/uploads/' +
file.filename,
r'H:/JS/uploads/' +
tag_name + '.json')
except:
logger.info("Renaming issue")
session['uploadFilePath']=destination
response="Congratulations, you have saved your file locally"
return response
@app.route("/get-file/<path:file_name>")
def get_file(file_name):
try:
print("Inside the Function")
return send_from_directory(app.config['UPLOAD_FILE'],filename=file_name, as_attachment= True)
except FileNotFoundError:
abort(404)
@app.route("/check")
def check_file():
for intent in data["intents"]:
for proficiency in intent["proficiency"]:
for questions in proficiency["questions"]:
if proficiency["level"] == "P1":
questionsP1.append(questions["question"])
questionTag[questions["question"]] = questions["tag"]
if proficiency["level"] == "P2":
questionsP2.append(questions["question"])
questionTag[questions["question"]] = questions["tag"]
if proficiency["level"] == "P3":
questionsP3.append(questions["question"])
questionTag[questions["question"]] = questions["tag"]
if proficiency["level"] == "P4":
questionsP4.append(questions["question"])
questionTag[questions["question"]] = questions["tag"]
with open(target + "/" + tag_name + ".json") as f:
data1 = json.load(f)
for intent in data1["intents"]:
for proficiency in intent["proficiency"]:
for questions in proficiency["questions"]:
if proficiency["level"] == "P1":
# questionsP1.append(questions["question"])
# questionTag[questions["question"]] = questions["tag"]
if(questions["question"] not in questionsP1):
a = {"tag": questionTag[questions["question"]],
"question": questions["question"],
"context_set":""}
questions.append(a)
logger.info(a)
if proficiency["level"] == "P2":
# questionsP2.append(questions["question"])
# questionTag[questions["question"]] = questions["tag"]
if(questions["question"] not in questionsP2):
b = {"tag": questionTag[questions["question"]],
"question": questions["question"],
"context_set":""}
questions.append(b)
logger.info(b)
if proficiency["level"] == "P3":
# questionsP3.append(questions["question"])
# questionTag[questions["question"]] = questions["tag"]
if(questions["question"] not in questionsP3):
c = {"tag": questionTag[questions["question"]],
"question": questions["question"],
"context_set":""}
questions.append(c)
logger.info(c)
if proficiency["level"] == "P4":
# questionsP4.append(questions["question"])
# questionTag[questions["question"]] = questions["tag"]
if(questions["question"] not in questionsP4):
d = {"tag": questionTag[questions["question"]],
"question": questions["question"],
"context_set":""}
questions.append(d)
logger.info(d)
write_json(data1)
return "true"
def write_json(data1):
logger.info(data1)
with open(target + "/" + tag_name + ".json" ,'w') as f:
json.dump(data1, f, indent=4)
app.secret_key = os.urandom(24)
这是我的json文件:-
{
"intents": [
{
"tech": "java",
"proficiency": [
{
"level": "P1",
"questions": [
{
"tag": "oops",
"question": "Name all oops concepts",
"responses": [
"Inheritance,Encapsulation,Polymorphism,Abstraction"
],
"context_set": ""
},
{
"tag": "final",
"question": "How can you ensure that class cannot be extended?",
"responses": [
"We can declare the class as final",
"By using final keyword",
"By making the class as final",
"by using final",
"by making it final"
],
"context_set": ""
},
{
"tag": "static",
"question": "What are the applications of static keyword?",
"responses": [
"Static Block, Static Variable, Static Method, Static Classes"
],
"context_set": ""
},
{
"tag": "access",
"question": "Name the various access specifiers in Java?",
"responses": [
"Public, Protected, Default, Private"
],
"context_set": ""
}
]
},
{
"level": "P2",
"questions": [
{
"tag": "order",
"question": "What will happen if I write 'static public void' instead of 'public static void'?",
"responses": [
"The program compiles and runs correctly because the order of specifiers doesn't matter in Java",
"It runs correctly",
"No issue"
],
"context_set": ""
},
{
"tag": "variables",
"question": "What is the default value of the local variables?",
"responses": [
"The local variables are not initialized to any default value, neither primitives nor object references",
"local variables are not initialized to any default value",
"local variables are not itiliazed"
],
"context_set": ""
},
{
"tag": "heirarchy",
"question": "Name the access modifiers in Java starting from the most restricted to the least restricted",
"responses": [
"Private, Default, Protected, Public"
],
"context_set": ""
}
]
},
{
"level": "P3",
"questions": [
{
"tag": "output",
"question": "What is the output of the following line? -> System.out.println(10 + 20 + 'Sum');",
"responses": [
"30Sum"
],
"context_set": ""
},
{
"tag": "private",
"question": "Can a class be private in Java?",
"responses": [
"Yes, Only inner classes",
"Yes"
],
"context_set": ""
},
{
"tag": "spring",
"question": "Name different scopes of Spring Bean",
"responses": [
"Singleton, Prototype, Request, Session, Global-Session"
],
"context_set": ""
}
]
},
{
"level": "P4",
"questions": [
{
"tag": "cons",
"question": "Does a contructor return anything?",
"responses": [
"Yes, The constructor implicitly returns the current instance of the class",
"Current instance"
],
"context_set": ""
},
{
"tag": "inheritence",
"question": "Is constructor inherited?",
"responses": [
"No"
],
"context_set": ""
},
{
"tag": "inheritence_new",
"question": "Can we send an Object as the response of Controller handler method?",
"responses": [
"Yes, using ResponseBody annotation",
"Yes"
],
"context_set": ""
}
]
}
]
}
]
}
我的目标是,如果要上传的文件已经存在,但是存在一些现有文件不存在的其他问题……。它将把这些额外的问题附加到其各自的位置。如果额外的问题在级别P1中,它将附加在该部分中,依此类推...
答案
一个可能的答案和一些信息:How to append data to a json file?
但要实际附加:
了解dict.update()函数:
import json
# JSON data:
x = '{ "organization":"GeeksForGeeks",
"city":"Noida",
"country":"India"}'
# python object to be appended
y = {"pin":110096}
# parsing JSON string:
z = json.loads(x)
# appending the data
z.update(y)
# the result is a JSON string:
print(json.dumps(z))
来源和信誉:https://www.geeksforgeeks.org/append-to-json-file-using-python/
更新:哦,是的,我看到您正在使用“从数据复制”实际需要更新data1中的数据的问题。示例:
example = [1,2,3,4]
for elemnt in example:
elemnt = 10
正在运行:
示例
将输出:[1、2、3、4]
因此在4个if之后,您需要更新data1。请记住,如果您通过以下方式访问字典或列表中的元素,请执行以下操作:对于target中的元素:该元素只是一个副本。
以上是关于附加到现有的json文件的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Excel 转换为 JSON 并将其附加到现有的 JSON 文件?
Jackson 不会将新的 JSON 对象附加到现有的 Json 文件中