Rohit Swami
Rohit Swami

Reputation: 316

how to parse JSON to get specific value in Python

Please consider the following data:

    {
      "-L0B6_KJJlhWIaV96b61" : {
                     "name" : "John",
                     "text" : "hey"
    },
      "-L0B6cN4SV59tuNVWh_1" : {
                     "name" : "Joe",
                     "text" : "hi"
    },
      "-L0B6epDdv1grl7t5kdM" : {
                     "name" : "John",
                     "text" : "good to see you..."
    },
      "-L0B6fsyjAm4B_CWXKFs" : {
                     "name" : "Joe",
                     "text" : "how are you?"
    }

Now how to parse the name and text from this JSON file in Python? I have a large dataset like this. As you can see the object is variable in this case so I can't simply write:

         # To print the name
         pprint(data[object_variable][0])

Please help me out in printing only name and text. Thanks

Upvotes: 2

Views: 1200

Answers (2)

user9158931
user9158931

Reputation:

Maybe you can try:

data={
      "-L0B6_KJJlhWIaV96b61" : {
                     "name" : "John",
                     "text" : "hey"
    },
      "-L0B6cN4SV59tuNVWh_1" : {
                     "name" : "Joe",
                     "text" : "hi"
    },
      "-L0B6epDdv1grl7t5kdM" : {
                     "name" : "John",
                     "text" : "good to see you..."
    },
      "-L0B6fsyjAm4B_CWXKFs" : {
                     "name" : "Joe",
                     "text" : "how are you?"
    }}

print(list(map(lambda x:(x['text'],x['name']),data.values())))

output:

[('good to see you...', 'John'), ('hi', 'Joe'), ('hey', 'John'), ('how are you?', 'Joe')]

Upvotes: 0

heemayl
heemayl

Reputation: 41987

If i understand correctly, use a list comprehension (or generator) to put the values of the dictionary:

[v for _, v in data.items()]

You can directly print or do operation, without using a intermediate list, of course.

So:

In [10]: d
Out[10]: 
{'-L0B6fsyjAm4B_CWXKFs': {'name': 'Joe', 'text': 'how are you?'},
 '-L0B6cN4SV59tuNVWh_1': {'name': 'Joe', 'text': 'hi'},
 '-L0B6_KJJlhWIaV96b61': {'name': 'John', 'text': 'hey'},
 '-L0B6epDdv1grl7t5kdM': {'name': 'John', 'text': 'good to see you...'}}

In [11]: [v for _, v in d.items()]
Out[11]: 
[{'name': 'Joe', 'text': 'how are you?'},
 {'name': 'Joe', 'text': 'hi'},
 {'name': 'John', 'text': 'hey'},
 {'name': 'John', 'text': 'good to see you...'}]

Upvotes: 2

Related Questions