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

2
  • 1
    "facing a lot of issuse". What issues? It's easier to correct a problem if we know what the problem is. Commented Oct 19, 2016 at 5: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, which was written by SO veteran Ned Batchelder. Commented Oct 19, 2016 at 6:22

1 Answer 1

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'>
Sign up to request clarification or add additional context in comments.

3 Comments

@abhi_bond . does this help ?
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.
As Hindi characters are unicode characters, the answer to this question stackoverflow.com/questions/18337407/… might help.

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.