Issue
I tried using an append to create a new array. However, either the created function returns an array with several objects and not an object with several values.
Code->
def parse_json(self, data):
file = 'vault.json'
json = {}
for obj in data:
if 'EMAIL' in obj[0]:
json.setdefault('EMAIL', []).append({obj[0]: obj[1]})
if 'TEST' in obj[0]:
json.setdefault('TEST', []).append({obj[0]: obj[1]})
else:
json.setdefault('VAULT', []).append({obj[0]: obj[1]})
with open(file, 'w') as f:
dump(json, f, indent=2, separators=(',', ':'))
Response ->
{
"EMAIL":[
{"EMAIL_CC":""},
{"EMAIL_CCO":""},
{"EMAIL_DESTINY":"teste@gmail.com"}
]
}
Desired answer ->
{
"EMAIL":{
"EMAIL_CC":"",
"EMAIL_CCO":"",
"EMAIL_DESTINY":"teste@gmail.com"
}
}
Solution
In python, the curly brackets { } are used for dictionaries, which are similar to javascript objects (which sounds like what you're familiar with). The hard brackets [ ] are called lists. Your desired response looks like a dictionary with a key that has a dictionary as its value. Unfortunately, you can't add key-value pairs into a list or array in python, so you should instead make another dictionary instead of a list or rethink what your desired list would look like (perhaps only the values and not the keys).
TL;DR: you are appending dictionaries to your list:
.append({obj[0]: obj[1]})
{obj[0]: obj[1]}
is a dictionary you are appending to the list.
In python you can have a list of dictionaries but you cant have just key-value pairs in a list
Answered By - jros Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.