簡體   English   中英

在Python中使用編碼發送JSON數據的正確方法

[英]Correct way of sending JSON Data with encoding in Python

我正在Django上開發API,並且在使用python在后端對數據進行編碼並在java的前端對數據進行解碼時遇到很多問題。

有任何有效將正確的JSON數據發送到客戶端應用程序的標准規則嗎?

有些前端無法正確接收印地語字符,它給出錯誤消息,指出“字符處的JSON未終止對象”,所以我想問題就在我這一邊

json.loadsjson.dumps通常用於在python中編碼和解碼JSON數據。

dumps一個對象並生成一個字符串,而load將使用一個類似文件的對象,從該對象讀取數據,然后使用該字符串創建一個對象。

編碼器默認理解Python的本機類型(字符串,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

值的編碼方式與Python的repr()輸出非常相似。

$ python json_simple_types.py

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

進行編碼,然后重新解碼可能無法提供完全相同類型的對象。

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'])

特別是,字符串被轉換為unicode,而元組成為列表。

$ 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'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM