简体   繁体   中英

converting JSON string into a python dictionary

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.

... 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"
        }
      ]
    }
  ]
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM