Home > Mobile >  How to parse JSON value in python
How to parse JSON value in python

Time:11-19

I am trying to get the active DB name, so I can then make a backup and store offline. When I run this below, I get an output of: [('Stillman-SP', False), ('initial.bak', False), ('initial', True)]

I only want to print the DB name, that has a value of True.

for item in status.json():
    tr = item ['dbName'], item ['active']
    table.append(tr)

status.json:

[
    {
        "dbName": "Test-SP",
        "active": false,
        "lastModified": "2021/11/15 20:13:21"
    },
    {
        "dbName": "initial.bak",
        "active": false,
        "lastModified": "2021/11/16 15:42:35"
    },
    {
        "dbName": "initial",
        "active": true,
        "lastModified": "2021/11/17 20:42:10"
    }
]

So I am calling an API. I don't have a json file path.

  s.get(get_active, verify=False, headers ={'Content-Type': 'application/json'}, cookies=r.cookies)

get_active is the variable name that holds the API url.

CodePudding user response:

Updated function

def append_active_databases_to_table(filename: str):
    with open(filename) as json_file:
        return [db['dbName'] for db in json.load(json_file) if db['active']]

print(append_active_databases_to_table('./status.json'))

Using map/filter (less efficient)

def append_active_databases_to_table(filename: str):
    with open(filename) as json_file:
        return list(map(lambda db: db['dbName'], filter(lambda db: db['active'], json.load(json_file))))

print(append_active_databases_to_table('./status.json'))

Test

def test_append_active_databases_to_table():
    table = append_active_databases_to_table('./status.json')

    assert len(table) == 1
    assert table[0] == 'initial'

status.json

[
  {
    "dbName": "Stillman-SP",
    "active": false
  },
  {
    "dbName": "initial.bak",
    "active": false
  },
  {
    "dbName": "initial",
    "active": true
  }
]
  • Related