0

I have an array that looks like:

  item =   [{'name': 'first'}, {'name': 'second', 'something': 'something4'},  {'name': 'third', 'hu': 'g'}]

I want to write a function that given a key it will return the json that contains the key. For example: by for first it will return {'name': 'first'} for third it will return {'name': 'third', 'hu': 'g'}

This is what I wrote so far

def func(obj, val_to_search , key_to_search):
    j = json.loads(item)
    for item in j:
        if j[key_to_search] = val_to_search
           return j

func(obj=item, val_to_search='first', key_to_search='name')

but this doesn't work. What am I doing wrong?

4
  • 1
    what you show is not list of json, but list of dicts. Doesn't work is not very helpful description of a problem. Please, provide minimal reproducible example Commented Sep 12, 2021 at 12:49
  • You are using single = instead of == please check these typo mistakes before posting Commented Sep 12, 2021 at 12:50
  • @U12-Forward, there are number of errors in the snippet and I am not sure this is correct duplicate Commented Sep 12, 2021 at 12:50
  • Can you please edit the question to clarify what you want to do? The description is about JSON and keys, the example about dicts and value, and the code about JSON and key-value pairs. Commented Sep 12, 2021 at 12:55

1 Answer 1

1

item is already a Python object:

item = [{
    'name': 'first'
}, {
    'name': 'second',
    'something': 'something4'
}, {
    'name': 'third',
    'hu': 'g'
}]


def func(obj, val_to_search, key_to_search):
    for item in obj:
        if item[key_to_search] == val_to_search:
            return item


res = func(obj=item, val_to_search='first', key_to_search='name')
print(res)

Out:

{'name': 'first'}
Sign up to request clarification or add additional context in comments.

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.