Search code examples
pythonjsonobjectpprint

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


Solution

  • 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...'}]