1

I am stuck with a silly problem.

I have a json data and trying to save it in my model.

Here is the code.

response = response.json() #this gives json data
response = json.loads(response) #loads string to json           
json_string = response #ready to get data from list
modelfielda = json_string.get("abc") # this works fine
modelfieldb = json_string.get('["c"]["d"]["e"]') #this does not give data though data is present.

My json data comes like this:

{  
   "abc":"AP003",
   "c":[  
      {  
         "d":{  
            "e":"some data",
            "f":"some data"
         }
      }
   ]
}

So my question is how to get data inside c.

7
  • What about bnm = json_string.get('c')? Commented May 3, 2018 at 14:32
  • @Chiefir That will give full list and not specific item in e. Commented May 3, 2018 at 14:33
  • 1
    Try this for e -> bnm = json_string.get('c').get('d').get('e') Commented May 3, 2018 at 14:33
  • @Chiefir, note that c is a list Commented May 3, 2018 at 14:34
  • @Chiefir It worked thanks. Commented May 3, 2018 at 14:35

2 Answers 2

2

Try this for e:
bnm = json_string.get('c').get('d').get('e')
or with list:
bnm = json_string.get('c')[0].get('d').get('e')

Sign up to request clarification or add additional context in comments.

Comments

1

By using multiple .gets:

bnm = json_string.get('c')[0].get('d').get('e')  # bnm = 'some data'

Or perhaps better (since it will error in case the key does not exists):

bnm = json_string['c'][0]['d']['e']  # bnm = 'some data'

Since you converted it to a Python dictionary, you basically work with a dictionary, and you can obtain the value corresponding to a key by using some_dict[some_key]. Since we here have a cascade of dictionaries, we thus obtain the subdictionary for which we again obtain the corresponding value. The value corresponding to c is a list, and we can obtain the first element by writing [0].

2 Comments

The answer is correct for my question. But in case there are multiple list inside c, one has to manually use [0] or there is any short code for that. Thanks
@SapnaSharma: well the question is what do you want to do with that lists? Return all elements, only the first one, but indeed, you should add [0], or we can write a function that solves the logic.

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.