abhi_bond
abhi_bond

Reputation: 211

Correct way of sending JSON Data with encoding in Python

I am developing API's on Django, and I am facing a lot of issues in encoding the data in python at the back-end and decoding it at front-end on java.

Any standard rules for sending correct JSON Data to client application efficiently?

There are some Hindi Characters which are not received properly on front end, it gives error saying that "JSON unterminated object at character" So I guess the problem is on my side

Upvotes: 0

Views: 1806

Answers (1)

Nihal Rp
Nihal Rp

Reputation: 480

json.loads and json.dumps are generally used to encode and decode JSON data in python.

dumps takes an object and produces a string and load would take a file-like object, read the data from that object, and use that string to create an object.

The encoder understands Python’s native types by default (string, unicode, int, float, list, tuple, dict).

import json

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
print 'DATA:', repr(data)

data_string = json.dumps(data)
print 'JSON:', data_string

Values are encoded in a manner very similar to Python’s repr() output.

$ python json_simple_types.py

DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}]
JSON: [{"a": "A", "c": 3.0, "b": [2, 4]}]

Encoding, then re-decoding may not give exactly the same type of object.

import json

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
data_string = json.dumps(data)
print 'ENCODED:', data_string

decoded = json.loads(data_string)
print 'DECODED:', decoded

print 'ORIGINAL:', type(data[0]['b'])
print 'DECODED :', type(decoded[0]['b'])

In particular, strings are converted to unicode and tuples become lists.

$ python json_simple_types_decode.py

ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}]
DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]
ORIGINAL: <type 'tuple'>
DECODED : <type 'list'>

Upvotes: 3

Related Questions