【问题标题】:The unknown escape character issue when using YAML in python在 python 中使用 YAML 时的未知转义字符问题
【发布时间】:2017-09-08 03:21:21
【问题描述】:

我有以下文本(pandas 数据框中的一个单元格)在将其转换为 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 指南中的其他相关问题,但无法弄清楚解决方案是什么。有人可以帮忙吗?

【问题讨论】:

  • 您似乎正在尝试应用 YAML 而不是 JSON。改用json.loads
  • @MaxU 谢谢!刚刚遇到类似的错误Invalid \escape: line 1 column 173
  • @MaxU:注意 YAML 是 JSON 的超集。也就是说,YAML 解析器将解析任何有效的 JSON 文档。
  • @larsks,谢谢!我不知道
  • @renakre:' 不需要转义(因为字符串用 引号括起来,所以 ' 没有什么特别之处)。如果你只是用"overall_feedback":"...and that's something I want to learn too. " 替换它,它就可以正常工作。

标签: python json pandas dictionary yaml


【解决方案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 在评论中所说,

' 不需要转义(因为字符串用引号括起来)

确实你的问题很难重现:

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': {}}

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 2011-06-25
    • 2022-10-05
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多