2016-08-21 47 views
0

我想加載一個json文件,然後試圖稍後解析它。然而,在輸出中,我不停地收到'u'字符。 我試圖用encoding ='utf-8'打開​​這個文件,它能夠解決這個問題。 我正在使用python 2.7。有沒有一種簡單的方法或解決方法可以忽略並獲得輸出中的'u'字符。如何擺脫Python輸出的Unicode字符?

import json 
import io 


with io.open('/tmp/install-report.json', encoding='utf-8') as json_data: 
    d = json.load(json_data) 
    print d 

O/P

{u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544,}} 

PS:我去低谷這篇文章Suppress the u'prefix indicating unicode' in python strings 但沒有爲Python 2.7的解決方案

+1

簡而言之:[** **無(http://stackoverflow.com/questions/761361 /抑制最uprefix-指示-Unicode的在-蟒-字符串)。 – Jan

+0

爲什麼它是一個問題? –

+0

Unicode與該問題無關。這是一個包含字符串的字典的Python('repr()')表示。如果您想以另一種格式(例如JSON)表示,則使用該格式的編碼器。 – bobince

回答

2

使用json.dumps和對其進行解碼轉換它串起來

data = json.dumps(d, ensure_ascii=False).decode('utf8') 
print data 
+0

@ cool77如果它解決了您的問題請標記爲正確的答案 – Naruto

+1

我試過解決方案。它有助於。但是我需要稍後在腳本中使用json.load中的字典'd'。通過使用json.dumps,我得到一個字符串,我不能像字典中那樣迭代/ – cool77

+0

因此,同時保存'd'字典和'data'字符串並使用您需要的任何一個字符串。 – bobince

0

u只是指示es是一個Unicode字符串。如果打印字符串,它不會顯示:

d = {u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544}} 

print 'Status:',d[u'install'][u'Status'] 

輸出:

Status: In Progress...