-1

How can I filter a JSON dataset and assign the specified returned object to a variable in Python?

Dataset:

{
id            : 121
email         : email1@email.com
firstName     : Jason
lastName      : Wright
accountStatus : active
},
{
id            : 122
email         : email2@email.com
firstName     : Carl
lastName      : John
accountStatus : active
},
{
id            : 123
email         : email3@email.com
firstName     : Ernie
lastName      : Smith
accountStatus : active
}

PowerShell Example if the above dataset above set to the variable $Data:

$User = $Data | Where-Object {$_.id -eq "123"}

This would return:

id            : 123
email         : email3@email.com
firstName     : Ernie
lastName      : Smith
accountStatus : active

How can I store that data in a variable for later reuse?

TylerH
  • 20,799
  • 66
  • 75
  • 101
curtcab
  • 73
  • 1
  • 2
  • 11
  • 2
    `return [x for x in the_list if x['id'] == the_id]` – mama Aug 20 '21 at 00:08
  • 1
    First of all your example is not valid JSON (keys and values must be quoted and the dicts must be inside a list). Once you fix that see [this](https://stackoverflow.com/questions/7771011/how-to-parse-data-in-json-format) and [this](https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search). – Selcuk Aug 20 '21 at 00:09

1 Answers1

1

If you convert the list to a dict it will be alot easier

import json

the_list = [
        {
            'id'            : 121,
            'email'         : 'email1@email.com',
            'firstName'     : 'Jason',
            'lastName'      : 'Wright',
            'accountStatus' : 'active',
            },
            {
            'id'            : 122,
            'email'         : 'email2@email.com',
            'firstName'     : 'Carl',
            'lastName'      : 'John',
            'accountStatus' : 'active',
            },
            {
            'id'            : 123,
            'email'         : 'email@email.com',
            'firstName'     : 'Ernie',
            'lastName'      : 'Smith',
            'accountStatus' : 'active',
            }
        ]

the_dict = {
        x['id']: {
            k:v for (k, v) in x.items()
            if k != 'id'
        }
        for x in the_list
    }

print(json.dumps(the_dict, indent=2))

_id = int(input('Put the id you want: \n'))

print(json.dumps(the_dict[_id], indent=2))
mama
  • 2,046
  • 1
  • 7
  • 24