gpt4 book ai didi

python - 值更新的 Json 写入问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:06 24 4
gpt4 key购买 nike

所以,这段代码的目的是用用户提供的信息创建一个 json,但在最内层的循环中,值总是更新为用户最后插入的值。

import json


while True:
keepGoing = True
pay_obj = {
'id': {0: {
}
}
}
pay_res = {
"res": {
}

}
pay_access = {
'type': 'type',
'acl': 'acl',
'value': ''
}
obj_id = str(input('Insert obj ID: '))
pay_obj[obj_id] = pay_obj['id']
while keepGoing == True:
print(pay_res)
res_id = str(input('Insert resource ID: '))
pay_res[res_id] = pay_res['res']
type = str(input(f'Insert the data type for {res_id}: '))
pay_access['type'] = type.upper()
acl = str(input(f'Insert the access control level for {res_id}: '))
pay_access['acl'] = acl.upper()
pay_res[res_id] = pay_access
cont = input('More resources?(y/n): ')
if cont == 'n':
pay_obj[obj_id]=pay_res
del pay_obj['id']
del pay_obj[obj_id]['res']
pay_obj = json.dumps(pay_obj,indent=4)
print(pay_obj)
del pay_obj
break

预期的输出应该是这样的 json

{
"3303": {
"3303": {
"type": "STRING",
"acl": "R",
"value": ""
},
"3304": {
"type": "STRING",
"acl": "W",
"value": ""
}
}
}

但使用正确的值,而不是资源中的最后一个值。

最佳答案

与 ncica 代码类似,我只是实现了一个额外的循环以在同一个 json 上引入更多对象:

import json

main={}

j=True
while j:
obj_id = str(input('Insert obj ID: '))
obj_temp={}
keepGoing = True
while keepGoing == True:
res_id = raw_input('Insert resource ID for object ID %s: ' % obj_id)
type = raw_input('Insert the data type for resource ID %s: '% res_id)
val = raw_input('Insert the value for resource ID %s: ' % res_id)
acl = raw_input('Insert the access control level for resource ID %s: ' % res_id)
tmp_res = {"type": type, "acl": acl.upper(), "value": val.upper()}
obj_temp[res_id]=tmp_res
cont = raw_input('More resources?(y/n): ')
if cont=='n':
keepGoing=False
cont1 = raw_input('More obj?(y/n): ')
main[obj_id]=obj_temp
if cont1=='n':
j=False
print main

例子:

Insert obj ID: 1
Insert resource ID for object ID 1: 10
Insert the data type for resource ID 10: type10
Insert the value for resource ID 10: value10
Insert the access control level for resource ID 10: access10
More resources?(y/n): y
Insert resource ID for object ID 1: 20
Insert the data type for resource ID 20: type20
Insert the value for resource ID 20: value20
Insert the access control level for resource ID 20: access20
More resources?(y/n): n
More obj?(y/n): y
Insert obj ID: 2
Insert resource ID for object ID 2: 30
Insert the data type for resource ID 30: type30
Insert the value for resource ID 30: value30
Insert the access control level for resource ID 30: access30
More resources?(y/n): n
More obj?(y/n): n

{
'1':{
'10':{
'type':'type10',
'value':'VALUE10',
'acl':'ACCESS10'
},
'20':{
'type':'type20',
'value':'VALUE20',
'acl':'ACCESS20'
}
},
'2':{
'30':{
'type':'type30',
'value':'VALUE30',
'acl':'ACCESS30'
}
}
}

关于python - 值更新的 Json 写入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com