2014-03-29 96 views
0

我有以下代碼,這是一個函數,用於將交易歷史從數字貨幣錢包導出到json文件。如何對JSON中的對象進行排序? (使用Python 2.7)

我所面臨的問題有兩個:

  1. 我想允許使用UTF-8 JSON文件,爲屬性「標籤」可以是UTF-8字符,如果我沒有說明這一點,它會在文件中顯示爲\ u \ u \ u等。但是,無論編碼/解碼('utf-8')的組合和順序如何,我都無法獲得最終輸出文件打印到utf-8。

  2. 我想按照我在代碼中編寫它們的順序來排序每個迭代。我試圖從OrderedDict收集,但使日期是第一位的,它沒有訂購的物品等

,首先要弄清楚如何使用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) 
+0

請僅發佈與問題相關的部分代碼 – thefourtheye

+0

@thefourtheye完成!感謝提醒 – user3074620

回答

2

您需要確保兩個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而不會將其更改爲簡單字典。看到區別:

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} 
0

要在UTF-8的使用ensure_ascii=False編碼所生成的JSON:

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!"' 
"привет!" 
>>> 

對於關於順序的第二個問題。這是不可能的(除非你寫自己的序列化),也沒有任何意義:Items in JSON object are out of order using "json.dumps"?

當你傳遞wallet_historyjson.dumps它已經失去了它的秩序,因爲它包含的字典,這是無序的。

+0

正如你所看到的,我確實有sure_ascii = False,它仍然不能用utf-8編寫......我想可能是因爲我先將轉儲存儲到一個字符串中?這與file.write()函數有關嗎?... – user3074620

+0

它在這裏工作(請參閱我的更新)。你如何檢查它仍然不能用utf-8編寫? – warvariuc

+0

我正在通過在設置爲utf8編碼的文本編輯器中打開文件進行檢查。只有標籤寫入/ u字節 – user3074620

相關問題