[英]using Python Trying to Increment the JSON object values in a Array before copying the object in a array in a new file
I have the following JSON which i am importing in python我有以下 JSON,我正在导入 python
[{
"title": "Reference Addition",
"ref_date": 20200110,
"country": "ASIA",
"ref_internal": "1",
"ref_external": "1"
}]
after import i have saved the data in a variable and changing the values of the JSON Objects to whats needed导入后,我将数据保存在一个变量中,并将 JSON 对象的值更改为所需的值
# open the file and load the data
with open(myfile, 'r') as f:
data = json.load(f)
changing the values of the objects with following通过以下方式更改对象的值
# edit the elements of the JSON Object array
for obj in data:
obj['title'] = ['title'] + 1
obj['ref_internal'] = ['ref_internal'] + 1
obj['ref_external'] = ['ref_external'] + 1
After changing i am copying the original data with changed values to a new file更改后,我将具有更改值的原始数据复制到新文件
# create n copies of the array
copied_data = [copy.deepcopy(data) for _ in range(n)]
and saving into a new file using this并使用它保存到一个新文件中
with open('JSON\NEW_DATA.json', 'w') as f:
json.dump(copied_data, f, indent =4)
but each time i want save the array i would like the above values to be incremented but i am struggling to get that done但每次我想保存数组时,我都希望上面的值增加,但我很难做到这一点
I keep getting this error for all the fields我不断收到所有字段的此错误
obj['title'] = ['title'] + 1
TypeError: can only concatenate list (not "int") to list
It might be a silly mistake but I am new to Python and JSON any help of guidance on how i can do that will really help me learn.这可能是一个愚蠢的错误,但我是 Python 和 JSON 的新手,任何关于我如何做到这一点的指导帮助都会真正帮助我学习。
I got it to work by using the copy and copy_num variable copied_obj["ref_internal"] = f"{obj['ref_internal']} - {copy_num}"我通过使用 copy 和 copy_num 变量 copied_obj["ref_internal"] = f"{obj['ref_internal']} - {copy_num}" 让它工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.