I want to extract JSON objects that have a specific key value pair present in them

Question:

I have a JSON response from an API that looks like this:

"get_result_by_result_id": [{
    "data": {
        "date_trunc": "2022-09-06T00:00:00+00:00",
        "project": "Smoothy Finance",
        "usd_volume": 42307.09145419092
    },
     
}, {
    "data": {
        "date_trunc": "2022-09-30T00:00:00+00:00",
        "project": "curve",
        "usd_volume": 40548.688138892685
    },
     
},  {
    "data": {
        "date_trunc": "2022-09-14T00:00:00+00:00",
        "project": " kyber",
        "usd_volume": 13800038.727002844
    },
     
},]

And I want to extract all objects in the response which have "kyber" value present in them like this:

"common_objects": [{
        "data": {
            "date_trunc": "2022-09-14T00:00:00+00:00",
            "project": " kyber",
            "usd_volume": 13800038.727002844
        },
         
    }, {
        "data": {
            "date_trunc": "2022-09-07T00:00:00+00:00",
            "project": " kyber",
            "usd_volume": 24518356.073168807
        },},]

How should I do this?

Asked By: ren

||

Answers:

I think your json is corrupted, so I edited it a bit and here’s how you can do it:

data = [{
    'data': {
        'date_trunc': '2022-09-06T00:00:00+00:00',
        'project': 'Smoothy Finance',
        'usd_volume': 42307.09145419092
    }

}, {
    'data': {
        'date_trunc': '2022-09-30T00:00:00+00:00',
        'project': 'curve',
        'usd_volume': 40548.688138892685
    }

},  {
    'data': {
        'date_trunc': '2022-09-14T00:00:00+00:00',
        'project': ' kyber',
        'usd_volume': 13800038.727002844
    }

}]

clear_data = []
for data in data:
    if(data['data']['project'] == ' kyber'):
        clear_data.append(data)

print(clear_data)
Answered By: Vitaliy Korolyk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.