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']
2
  • 1
    What symptom are you getting when you run your code? Commented Oct 17, 2019 at 9:56
  • 1
    post['data'] is a list you need to iterate over it to get the answer Commented Oct 17, 2019 at 9:56

5 Answers 5

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']
Sign up to request clarification or add additional context in comments.

1 Comment

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
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'])

Comments

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

Comments

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

Comments

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'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.