Home > Software engineering >  Convert the existing disctionary output in string to a list to iterate over it
Convert the existing disctionary output in string to a list to iterate over it

Time:04-20

I have a rest api which provides a list of key value pair's and we need to fetch all the id's from this json output file.

Contents of the json file

{
  "count": 2,
  "results": [
    {
      "key": "workspace_resources",
      "id": "321214199"
    },
    {
      "key": "workspace_resources",
      "id": "321214195"
    }
    {
      "key": "workspace_resources",
      "id": "321214196"
    }
    {
      "key": "workspace_resources",
      "id": "321214198"
    }
    {
      "key": "workspace_resources",
      "id": "321214299"
    }
    {
      "key": "workspace_resources",
      "id": "3212141035"
    }
    {
      "key": "workspace_resources",
      "id": "321214105"
    }
    {
      "key": "workspace_resources",
      "id": "321214191"
    }    {
      "key": "workspace_resources",
      "id": "321214190"
    }    {
      "key": "workspace_resources",
      "id": "321214193"
    }

  ],

The rest call saves the contents to a file called p1234.json Opened the file in python:

with open ('p1234.json') as file:
    data2 = json.load(file)

for ids in data2['results']:
    allocation = ids['id']
    print(allocation)
print(type(allocation))


Output is as follows:

python .\1.py
123697401
123697403
123697404
123697405
123697406
123957117
123957491
123983488
124074207
124128552
124128553
124203018
124229335
124230125
124246767
124272164
124272180
124380726
124397894
124397895
<class 'str'>

How to convert the entire output into a list, so i can iterate over this list and perform an action on each item ????

Thank you

CodePudding user response:

id_list = []
for ids in data2['results']:
    id_list.append(ids['id'])
print(id_list)

CodePudding user response:

This code should convert it to list!

data2 = json.load(open('p1234.json'))
mylist = [x["id"] for x in data2["results"]]

Or you can iterate over the JSON without converting it to list. See https://www.delftstack.com/howto/python/iterate-through-json-python/

CodePudding user response:

If you are OK with using pandas you can do it in one line....

import pandas as pd
id_list = pd.DataFrame(data2['results']).id.values.tolist()
  • Related