[英]Update specific JSON file parameter after searching for it's value from other file through Python
I'm trying to update a specific parameter of JSON file after referencing another data file (can be of any format text, ruleset etc) through Python.在通过 Python 引用另一个数据文件(可以是任何格式的文本、规则集等)后,我正在尝试更新 JSON 文件的特定参数。
The JSON file ' sample.json ' is: JSON 文件“ sample.json ”是:
{'Main': {'Attribute': {'Type': 'X::Y::Z', 'Dictionary': {'Object': {'Key1': false, 'Key2': false}}}}}
The content of data file ( requirements.ruleset / requirements.txt ) is:数据文件( requirements.ruleset / requirements.txt )的内容是:
X::Y::Z Dictionary == {"Key1": true, "Key2": true}
The python code that manually updates the value of "Key1": true
& "Key2": true
python 代码手动更新"Key1": true
& "Key2": true
的值
import json
a_file = open("sample.json", "r")
json_object = json.load(a_file)
a_file.close()
print(json_object)
#Manual way to update the value of Key1 & Key2 to be "true"
json_object["Main"]["Attribute"]["Dictionary"]["Object"]["Key1"] = "true"
json_object["Main"]["Attribute"]["Dictionary"]["Object"]["Key"] = "true"
a_file = open("sample_file.json", "w")
json.dump(json_object, a_file)
print(json_object)
a_file.close()
It correctly updates the sample.json file with the value of "Key1": true
& "Key2": true
.它正确更新了 sample.json 文件,其值为"Key1": true
& "Key2": true
。 Updated sample.json file更新了 sample.json 文件
{'Main': {'Attribute': {'Type': 'X::Y::Z', 'Dictionary': {'Object': {'Key1': 'true', 'Key2': true}}}}}
How can I update the values of the Key1 & Key2 to "true" automatically by referencing (requirements.ruleset / requirements.txt) !如何通过引用(requirements.ruleset / requirements.txt)自动将 Key1 和 Key2 的值更新为“true”! Thank you in advance!!先感谢您!!
This code will work.此代码将起作用。 And there are some changes to be made in your txt and json files.您的 txt 和 json 文件需要进行一些更改。 Copy from the code I give.从我给出的代码中复制。
Code:- sample.json代码:- sample.json
{"Main": {"Attribute": {"Type": "X::Y::Z","Dictionary": {"Object": {"Dictionary": {"Key1": false,"Key2": false}}}}}}
Code:- requirements.json (Make is requirements.json instead of txt)代码:- requirements.json (Make is requirements.json 而不是 txt)
{"Dictionary" :{"Key1": true, "Key2": true}}
Code:- name.py代码:-name.py
import json
def write_json(new_data, filename='sample.json'):
with open(filename,'r+') as file:
file_data = json.load(file)
content['Main']['Attribute']['Dictionary']['Object'] = abcd
file_data.update(content)
file.seek(0)
json.dump(file_data, file)
a_file = open("sample.json", "r+")
content = json.load(a_file)
f = open('requirements.json', 'r')
abcd = json.load(f)
write_json(abcd)
print('Done!')
It worked in my.它在我的工作。 It will defenitely work in yours ok!它肯定会在你的工作中正常工作!
Don't forget to convert the txt file to json.不要忘记将 txt 文件转换为 json。
Happy coding!快乐编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.