-1

I'm currently deveolping an Android application that has Django framework as it's server side.

When i'm posting a data of a new user to my database i am POSTing a multipart request that has a user part inside. The user for some reason is represented as a list but when i take it out of the request.data['user'] it's a str instance (Yea i dont know why...)

When i fetch that str i started working on it with json package. I looked up on the internet (to many places..) how to convert a string in json format to a dictionary.

What i found is that when you use the json.loads command it doesn't give a dict back but a str instance :)

This is the code on my server side when i enter the create function of the ModelViewSet that handles the creation of the user.

userJson = request.data['user']
userJson = json.dumps(userJson)
userJson = json.loads(userJson)

What i tried to do is to make a string of my own in JSON format and that called the json.loads() command which gave me the dict object.. There seems to be a problem with processing the str from the http request of django rest framework for some reason or there's something else i am not seeing.

I tried the following links - Converting JSON String to Dictionary Not List

http://docs.python-guide.org/en/latest/scenarios/json/

Didn't worked also..

Now, i tried accessing the str i got from json.loads() like a dictionary in this way.

id = userJson['id']

Now lets say maybe i passed a wrong json format to the loads function, it should have thrown an exception.. The code above (getting the id) raised an exception of 'String indices must be integer' - it doesn't convert it to dict! LOL xD

Good note worth mentioning - I'm trying to convert the json to a dictionary so i could access it like this - dictObject['id']

Well i would really appreciate every help! Thanks :)

Community
  • 1
  • 1
Ido Magor
  • 544
  • 1
  • 5
  • 14
  • Why do you `dump` and then `loads`? What's exactly in `request.data['user']`? – Shang Wang Jan 20 '16 at 18:23
  • If i don't do dumps before loads it raises an exception of - ValueError('extra data') and that it couldn't find the children... the request.data['user'] is showed to be a list type(i wrote in the question...) – Ido Magor Jan 20 '16 at 18:27
  • When i fetch the request.data['user'] it has only 1 item of the json from my android client so it puts the json inside the userJson and then i am trying to convert it to a dictionary. – Ido Magor Jan 20 '16 at 18:28

1 Answers1

0

For some reason , when i did this commands-

userJson = request.data['user']
userJson = json.loads(userJson)
userJson = json.loads(userJson)

What i got to have inside the userJson after the second json.loads(userJson) I got the actual dict object to the userJson member. Appearently it is a bug.

21 January - another update, I truly was doing double Json encoding on the Android application so that was the reason for double json. loads()

Ido Magor
  • 544
  • 1
  • 5
  • 14