2

I have a JSON file where each object looks like the following example:

[
  {
    "timestamp": 1569177699,
    "attachments": [

    ],
    "data": [
       {
         "post": "\u00f0\u009f\u0096\u00a4\u00f0\u009f\u0092\u0099"
       },
       {
         "update_timestamp": 1569177699
       }
    ],
    "title": "firstName LastName"
  }
]

I want to check if, there is the key post, nested within the key data. I wrote this, but it doesn't work:

 posts = json.loads(open(file).read())
 for post in posts:
     if 'data' in post:
        if 'post' in post['data']
            print post['data']['post']
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
Lx2pwn
  • 313
  • 4
  • 11

5 Answers5

3

Here is my solution. I see from your sample data that post["data"] is a list, so the program should iterate over it:

posts = json.loads(open(file).read())
    for post in posts:
        if 'data' in post:
            #THIS IS THE NEW LINE to iterate list
            for d in post["data"]:
                if 'post' in d:
                    print d['post']
quamrana
  • 37,849
  • 12
  • 53
  • 71
Wonka
  • 1,548
  • 1
  • 13
  • 20
  • 1
    You are welcome, it was not a problem at all. Im glad I could be of assistance and its nice to hear thanks when you help somebody on this days – Wonka Oct 17 '19 at 14:50
0

Try:

posts = json.loads(open(file).read())
for data in posts:
    for key, value in data.items():
        if key == 'data':
            for item in value:
                if 'post' in item:
                    print(key, item['post'])
Chüngel
  • 375
  • 4
  • 19
0

Try this answer this works!

Elegant way to check if a nested key exists in a python dict

def keys_exists(element, *keys):
    '''
    Check if *keys (nested) exists in `element` (dict).
    '''
    if not isinstance(element, dict):
        raise AttributeError('keys_exists() expects dict as first argument.')
    if len(keys) == 0:
        raise AttributeError('keys_exists() expects at least two arguments, one given.')

    _element = element
    for key in keys:
        try:
            _element = _element[key]
        except KeyError:
            return False
    return True
Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
0

You could do it generically by adapting my answer to the question How to find a particular json value by key?.

It's generic in the sense that it doesn't care much about the details of how the JSON data is structured, it just checks every dictionary it finds inside it.

import json

def find_values(id, json_file):
    results = []

    def _decode_dict(a_dict):
        try:
            results.append(a_dict[id])
        except KeyError:
            pass
        return a_dict

    json.load(json_file, object_hook=_decode_dict)  # Return value ignored.
    return len(results) > 0  # If there are any results, id was found.

with open('find_key_test.json', 'r') as json_file:
    print(find_values('post', json_file)) # -> True
martineau
  • 119,623
  • 25
  • 170
  • 301
0

please try the following:

posts = json.loads(open(file).read())

for post in posts:
    if 'data' in post:
        for data in post['data']:
            if 'post' in data:
                print(data['post'])