skip to Main Content

Given an array of JSON objects as:

arr=[{"id": "abc", "value": "123"}, {"id": "xyz", "value": "456"}]

I would like to output a single JSON object like:

new_arr={"abc":123,"xyz":456}

Currently I can extract the elements like arr[0]['id'] but I am wondering what’s the one-liner or better way to form the output.

4

Answers


  1. A one-liner to extract the ids and values would be like this:

    new_arr = {item['id']: int(item['value']) for item in arr}
    

    as the arr object contains the value as a str you need to convert it to an int(). The rest of the one line similar to a list comprehension with dict as the base element to add to, thereby being a dict comprehension. Though this assumes that all dicts have a id and value combination (which is unknown from your data and am assuming that they always have an id and value)

    Login or Signup to reply.
  2. One alternative, showing the versatility of itemgetter:

    from operator import itemgetter
    
    arr = [{"id": "abc", "value": "123"}, {"id": "xyz", "value": "456"}]
    
    # itemgetter creates a function to extract the values at id and value
    pair = itemgetter("id", "value")
    
    # use map to apply the function to each element of arr
    d = dict(map(pair, arr))
    
    # print the result
    print(d)
    

    Output

    {'abc': '123', 'xyz': '456'}
    
    Login or Signup to reply.
  3. One line solution can be this:

    new_arr = {item['id']: int(item['value']) for item in arr}
    

    Or you can use itemgetter opertaror:

    new = dict(map(itemgetter("id", "value"), arr))
    
    Login or Signup to reply.
  4. Minimum code I think

    arr = [{"id": "abc", "value": "123"}, {"id": "xyz", "value": "456"}]
    json = {item['id']: item['value'] for item in arr}
    print(json)
    

    result:

    {'abc': '123', 'xyz': '456'}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search