0

I have following python dictionary object(json schema) - A which is a list of dictionary elements-

[
  {
    "id": 101, 
    "type": "fruit", 
    "name": "apple"
  },
  {
    "id": 102, 
    "type": "fruit", 
    "name": "mango"
  },
  {
    "id": 103, 
    "type": "vegetable", 
    "name": "cabbage"
  },
  {
    "id": 104, 
    "type": "vegetable", 
    "name": "carrot"
  }
]

Can somebody tell me how can I manipulate this list of dictionary object as I want following as the output B :-

[
  {
    "id": 102, 
    "type": "fruit", 
    "name": "mango"
  }
]

I tried doing this :-

import json

for myObj in A:
   if myObj['id'] == 102:
      myVal = myObj
test = json.dumps(myVal)
my_op = json.loads(test)

but this is not working as it is returning me "unicode" as type but I want dictionary "list" as its type.

Solution:-

import json

for myObj in A:
   if myObj['id'] == 102:
      myVal = [myObj] # Add myObj to list again which fixes the issue
test = json.dumps(myVal)
my_op = json.loads(test)
COD3R
  • 129
  • 9

2 Answers2

3
import json

for myObj in A:
   if myObj['id'] == 102:
      myVal = [myObj]
test = json.dumps(myVal)
B = json.loads(test)
print B
German Petrov
  • 1,475
  • 1
  • 17
  • 21
1

You need to put myVal into a list again:

myVal = [myObj]

This produces:

[{u'type': u'fruit', u'id': 102, u'name': u'mango'}]

after running it through json.dumps() / json.loads(). The Unicode strings are entirely normal; JSON uses Unicode strings throughout.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343