I am trying to add a new nested key to a json object but i can't seem to get it working and not sure what i am doing wrong. I'd also like to know that is the most efficient method for this?
def create_file(qle_folder, param_values):
json_list= []
files = [os.path.join(qle_folder, f) for f in os.listdir(folder) if os.path.isfile(os.path.join(qle_folder, f))]
for filename in files:
with open(filename) as f:
for l in f:
doc = json.loads(l)
target_length = len(doc['targets'])
if target_length == 0:
continue
labelel_dict ={}
for i in range(target_length):
label = doc['targets'][i]['label'].strip().lower()
match = doc['targets'][i]['match'].strip().lower()
new_dict = {
'type': label,
'value': match
}
key_value = str(d).strip().lower()
key_value = json.dumps(key_value)
if key_value in values_dict:
value = values_dict[key_value]
value = str(value).strip("[]\"").lower()
#dLabel = {"distros": {"Tags": { label: []}}}
label_dict[label] = value
doc['Options'] =''
doc['Options']['Tags']= label_dict
#doc['Options'] = d['Options']
doc = json.dumps(doc)
print(doc)
json_list.append(doc + '\n')
return json_list
The final file should look like:
{
"targets": [
{
"start": 40,
"end": 73,
"label": "test:image",
"match": "the cathedral"
}
{
"start": 40,
"end": 74,
"label": "test:text",
"match": "some text"
}
],
"Options": {
"Tags": {
"test:image": [
"test 1",
"test 3",
"test 4",
]
"test:text": [
"test 1",
"test 3",
"test 4",
]
}
}
}
The value_dict looks something like this and contains a key that is a "type" and "value" concatenated:
{"type": "test:image", "value": "the cathedral"}["['test 1']"]
{"type": "test:text", "value": "some text"}["['test 3']"]
The error I receive is
TypeError: 'str' object does not support item assignment
You initialize d
as a list but then attempt to access it as a dictionary. That line should be:
d = {}
If you need it to be a list, then you need to set the following lines differently:
new_dict = {
'type': label,
'value': match
}
It also looks like you are trying to replace single quotes with double quotes and I'm not sure why. You can use the json.dumps(d)
function to return a valid string representation of the dictionary in JSON.
It appears you are converting the values to a string and then evaluating them. As a dictionary you should not need to do that. I dont quite understand what you are trying to do with the key_values part.. Would the following not suffice:
for x in new-dict.keys():
if x in key_values:
// Do something
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.