簡體   English   中英

如何在JSON中對對象內的對象進行排序? (使用Python 2.7)

[英]How do I sort objects inside of objects in JSON? (using Python 2.7)

我有以下代碼,這是一個將交易歷史從數字貨幣錢包導出到json文件的功能。

我面臨的問題有兩個:

  1. 我想允許json文件用utf-8編寫,因為屬性'label'可以是utf-8字符,如果我不考慮它,它將在文件中顯示為\\ u \\ u但是,無論編碼/解碼('utf-8')的組合和順序如何,我都無法將最終輸出文件打印到utf-8。

  2. 我想按照我在代碼中編寫它們的順序來命令每次迭代。 我從集合中嘗試過OrderedDict,但是它沒有訂購這些項目以便Date首先出現,等等。

任何幫助,弄清楚如何使用utf-8打印到我的文件,並在我寫的每個項目內的順序。

非常感謝你。

# This line is the last line of a for loop iterating through
# the list of transactions, "for each item in list"
wallet_history.append({"Date": time_string, "TXHash": tx_hash, "Label": label, "Confirmations":
                      confirmations, "Amount": value_string, "Fee": fee_string, "Balance": balance_string})
try:
    history_str = json.dumps(
        wallet_history, ensure_ascii=False, sort_keys=False, indent=4)
except TypeError:
    QMessageBox.critical(
        None, _("Unable to create json"), _("Unable to create json"))
    jsonfile.close()
    os.remove(fileName)
    return
jsonfile.write(history_str)

您需要確保兩個json都不轉義字符,並將json輸出寫為unicode:

import codecs
import json

with codecs.open('tmp.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps({u'hello' : u'привет!'}, ensure_ascii=False) + '\n')


$ cat tmp.json
{"hello": "привет!"}

至於你的第二個問題:你可以使用collections.OrderedDict ,但你需要小心將它直接傳遞給json.dumps而不將其改為簡單的dict。 看到不同:

from collections import OrderedDict
data = OrderedDict(zip(('first', 'second', 'last'), (1, 10, 3)))
print json.dumps(dict(data)) # {"second": 10, "last": 3, "first": 1}
print json.dumps(data) # {"first": 1, "second": 10, "last": 3}

要使用UTF-8編碼生成的JSON,請使用ensure_ascii=False

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
>>> import json
>>> json.dumps(u'привет!', ensure_ascii=False)
u'"\u043f\u0440\u0438\u0432\u0435\u0442!"'
>>> print json.dumps(u'привет!', ensure_ascii=False)
"привет!"
>>> with open('test', 'w') as f:
...     f.write(json.dumps(u'привет!', ensure_ascii=False))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-6: ordinal not in range(128)
>>> with open('test', 'w') as f:
...     f.write(json.dumps(u'привет!'.encode('utf-8'), ensure_ascii=False))
... 
>>> with open('test') as f:
...     f.read()
... 
'"\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!"'
>>> print '"\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!"'
"привет!"
>>>

關於訂單的第二個問題。 這是不可能的(除了編寫自己的序列化程序)或它沒有意義: 使用“json.dumps”JSON對象中的項目是亂序的?

當你將wallet_history傳遞給json.dumps它已經丟失了它的順序,因為它包含無序的字典。

暫無
暫無

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

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