MuCh
MuCh

Reputation: 113

Difference between a python dictionary object and what json.loads return

I have a question about the difference between a plain Python dictionary object and what is returned as output of json.loads(str). As per checking type() on both the objects, it says dict. But i want to confirm this if json.load() actually returns a plain dict or a json object which is in dictionary format. My code is as below :

import json
my_dict={'key1': 'val1', 'key2': 'val2'}
my_json_string = json.dumps(my_dict)
resp_json=json.loads(my_json_string)
print(type(my_dict))
print(type(resp_json))

Output says : class 'dict' for both

But as menioned, I want to confirm if both are exactly the same thing, because I need to send back a JSON response and if both are exactly same, doesnt make sense to first convert it into a string using json.dumps() and then again do a json.loads() on it. I might as well return my dictionary object my_dict that I created. Hope my question is clear.

Upvotes: 2

Views: 4451

Answers (3)

mugetsu
mugetsu

Reputation: 198

json module use this conversion table

https://docs.python.org/2/library/json.html#json-to-py-table

+---------------+-----------+
|     JSON      |  Python   |
+---------------+-----------+
| object        | dict      |
| array         | list      |
| string        | unicode   |
| number (int)  | int, long |
| number (real) | float     |
| true          | True      |
| false         | False     |
| null          | None      |
+---------------+-----------+

Upvotes: 1

MTTI
MTTI

Reputation: 411

The preferred way of validating/checking a python object's type is isintance()

isinstance(resp_json, type(my_dict))

I suspect however, that the misconception here is another.

As I pointed out in my comment, json.loads() returns a dictionary, iff a string representing syntactically correct JSON is passed. Therefor the type dict is correct, because this is python's built in way of representing key-value information in a similar way to how JS/JSON does.

If you want to know, whether they are the same object, i.e. stored in the same place in memory, you can use

  resp_json is my_dict

Judging by your question, however I suspect that what you are really interested in, is the equivalence of the contents.

resp_json == mydict 

should give you this. I can't really immagine another scenario, which would mattter.

Upvotes: 0

Eran
Eran

Reputation: 2424

Both will be of type dict, but they are not the same dictionary, nor necessarily exactly equal.

For example, the json will contain unicode strings. In python 2, my_dict will not (it will str type). in this case my_dict['key1'] is not exactly the same as resp_json['key1'].

As an aside, for most things pythonic, this difference should not matter and you might consider them the same. Still, it's important to keep in mind the possible differences and consider if you are dealing with an edge-case where it matters.

Upvotes: 2

Related Questions