I have been tasked to create a JSON string which I then need to convert into a python dictionary.
I am just getting errors about extra data and I am unsure what to do next
import json
company = '{"Name": "George", "Manages": ["James", "Jamilia"]}, {"Name": "James", "Manages": ["Jill", "Jenny"]}, {"Name": "Jamilia", "Manages": ["Jasmine", "Jewel", "Jenny"]}'
company_dict = json.loads(company)
The task I am trying to complete is the following question: George runs a company. He manages James and Jamila, who each have a small team to manage. In James' team are Jill and Jenny. In Jamila's team are Jewel, Jasmine and Jeremy.
Create a JSON object in a string variable called company where each item has a name field and a field called manages which contains an array of the people managed by that person. If a person does not manage anybody, they have no field called manages.
Then convert the JSON string to a dictionary in a variable called company_dict.
-
2That isn't valid JSON, as you have several objects separated by commas but they aren't in an array. Should they be?ndc85430– ndc854302022年11月13日 15:46:33 +00:00Commented Nov 13, 2022 at 15:46
-
No, I want the initial part to be valid JSON - and then to convert that into a python dict.GLM– GLM2022年11月13日 15:53:51 +00:00Commented Nov 13, 2022 at 15:53
-
If you have several items, they either need to be in an array or another object (associated with keys, obviously). See json.org for what constitutes valid JSON.ndc85430– ndc854302022年11月13日 16:04:47 +00:00Commented Nov 13, 2022 at 16:04
-
Still can't work it out, I'm afraid.GLM– GLM2022年11月13日 16:19:44 +00:00Commented Nov 13, 2022 at 16:19
-
I'm not sure what to tell you. You can't have valid JSON for several items not in an array or an object. That's all there is to it, really.ndc85430– ndc854302022年11月13日 16:32:23 +00:00Commented Nov 13, 2022 at 16:32
1 Answer 1
... each item has a name field and a field called manages which contains an array of the people managed by that person. If a person does not manage anybody, they have no field called manages.
That sounds like an organization tree. Each employee has a name and optionally who they manage:
import json
from pprint import pprint
company = '''{"name": "George",
"manages": [{"name": "James",
"manages": [{"name": "Jill"},
{"name": "Jenny"}]},
{"name": "Jamila",
"manages": [{"name": "Jewel"},
{"name": "Jasmine"},
{"name": "Jeremy"}]}]}'''
dct = json.loads(company)
pprint(dct, sort_dicts=False)
print()
print(json.dumps(dct, indent=2))
Output:
{'name': 'George',
'manages': [{'name': 'James',
'manages': [{'name': 'Jill'}, {'name': 'Jenny'}]},
{'name': 'Jamila',
'manages': [{'name': 'Jewel'},
{'name': 'Jasmine'},
{'name': 'Jeremy'}]}]}
{
"name": "George",
"manages": [
{
"name": "James",
"manages": [
{
"name": "Jill"
},
{
"name": "Jenny"
}
]
},
{
"name": "Jamila",
"manages": [
{
"name": "Jewel"
},
{
"name": "Jasmine"
},
{
"name": "Jeremy"
}
]
}
]
}