Hyperion
Hyperion

Reputation: 2625

Python - Access Json value by another value

folders_list = {
   "folders": [{
   "id": "866699",
   "name": "Folder1",
    "files_count": 0,
    "size": "0",
    "has_sub": false
    }, {
    "id": "866697",
    "name": "Folder2",
    "files_count": 0,
    "size": "0",
    "has_sub": false
  }]

I need to get the folder id knowing the folder name. I thought that I could convert the json into a python dictionary and do

folder_id = [f['id'] for f in folders_list if f['name'] == 'Folder2'][0]

But Python doesn't let me convert it into a dictionary because it doesn't recognize "true" and "false" values.

Upvotes: 0

Views: 37

Answers (1)

user3657941
user3657941

Reputation:

The json library can handle false and true in the data:

import json

json_str = """
{
   "folders": [{
   "id": "866699",
   "name": "Folder1",
    "files_count": 0,
    "size": "0",
    "has_sub": false
    }, {
    "id": "866697",
    "name": "Folder2",
    "files_count": 0,
    "size": "0",
    "has_sub": false
  }]
}
"""

data = json.loads(json_str)
folders_list = data['folders']
folder_id = [f['id'] for f in folders_list if f['name'] == 'Folder2'][0]
print "folder_id = %s" % folder_id

Output

folder_id = 866697

Upvotes: 1

Related Questions