2017-04-12 15 views
0

使用YAML當我有它轉換成JSON字典類型時產生麻煩以下文本(以大熊貓數據幀的小區之一):未知的轉義字符問題蟒蛇

{"options_selected":{"Ideas":"0"},"criterion_feedback":{}, 
    "overall_feedback":"...and that\'s something I want to learn too. ", 
    "submission_uuid":"b195603a-60f5-11e4-95a7-0a7da95da37f"} 

我的代碼使用是這樣的:

df['POST'] = df['POST'].apply(yaml.load) 

它引發以下錯誤:

found unknown escape character "'" 
    in "<unicode string>", line 1, column 174: 
    ... that\'s something I want to learn too ... 

當我打印特定細胞,這是我得到

df.ix[7, 'POST'] 

>> that\\\'s 

我已經檢查了SO和YAML指南已經其他相關的問題,但無法找出解決的辦法是什麼。有人可以幫忙嗎?

+0

它看起來像你試圖應用'YAML'而不是'JSON'。試試'json.loads'而不是 – MaxU

+0

@MaxU謝謝!剛剛得到了一個類似的錯誤'無效\轉義:第1行第173列'! – renakre

+2

@MaxU:請注意,YAML是JSON的超集。也就是說,YAML解析器將解析任何有效的JSON文檔。 – larsks

回答

1

您必須先刪除轉義字符,因爲JSON不允許它。

import json 

j = '{"options_selected":{"Ideas":"0"},"criterion_feedback":{}, "overall_feedback":"...and that\'s something I want to learn too. ", "submission_uuid":"b195603a-60f5-11e4-95a7-0a7da95da37f"}' 

json.loads(j.replace("\\'", "'")) 

編輯:

爲@larks中的評論稱,

that ' doesn't need to be escaped (because the string is enclosed in double quotes)

,事實上你的問題是難以重現:

import yaml 
import json 

data = """ 
    options_selected: 
     Ideas: '0' 
    criterion_feedback: {} 
    overall_feedback": ...and that\'s something I want to learn too. , 
    submission_uuid : b195603a-60f5-11e4-95a7-0a7da95da37f 
""" 

print yaml.load(data) 

j = '{"options_selected":{"Ideas":"0"},"criterion_feedback":{}, "overall_feedback":"...and that\'s something I want to learn too. ", "submission_uuid":"b195603a-60f5-11e4-95a7-0a7da95da37f"}' 

print json.loads(j) 

將兩個輸出:

{'overall_feedback"': "...and that's something I want to learn too. ,", 'submission_uuid': 'b195603a-60f5-11e4-95a7-0a7da95da37f', 'options_selected': {'Ideas': '0'}, 'criterion_feedback': {}}