0

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

Soviut
  • 88,194
  • 49
  • 192
  • 260
abhi_bond
  • 211
  • 1
  • 2
  • 9
  • 1
    "facing a lot of issuse". What issues? It's easier to correct a problem if we know what the problem is. – Mark Tolonen Oct 19 '16 at 05:48
  • You need to tag your question with the Python version you're using: Unicode handling differs between Python 2 & Python 3. You should also paste some typical data into your question, as well as the Python code you are using to encode it to JSON. You may find this article helpful: [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Oct 19 '16 at 06:22

1 Answers1

3

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'>
Nihal Rp
  • 484
  • 6
  • 15
  • @abhi_bond . does this help ? – Nihal Rp Oct 19 '16 at 05:58
  • Thanks nihal for such a good explanation, but the problem is the encoding issues of string, I am not able to encode Hindi characters properly . sorry, I forgot to mention earlier. – abhi_bond Oct 19 '16 at 06:02
  • As Hindi characters are unicode characters, the answer to this question http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence might help. – Nihal Rp Oct 19 '16 at 06:19