【问题标题】:Parsing XML using json raises ValueError使用 json 解析 XML 会引发 ValueError
【发布时间】:2015-08-20 13:40:27
【问题描述】:

我正在尝试使用 xml ElementTree 和 json 解析 XML 文件

from xml.etree import ElementTree as et
import json

def parse_file(file_name):
    tree = et.ElementTree()
    npcs = {}
    for npc in tree.parse(file_name):
        quests = []
        for quest in npc:
            quest_name = quest.attrib['name']
            stages = []
            for i, stage in enumerate(quest):
                next_stage, choice, npc_condition = None, None, None
                for key, val in stage.attrib.items():
                    val = json.loads(val)
                    if key == 'choices':
                        choice = val
                    elif key == 'next_stage':
                        next_stage = val
                    elif key == 'ncp_condition':
                        npc_condition = {stage.attrib['npc_name']: val}
                stages.append([i, next_stage, choice, npc_condition])
            quests.append( {quest_name:stages})
        npcs[npc.attrib['name']] = quests
    return npcs

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<npcs>
    <npc name="NPC NAME">
        <quest0 name="Quest Name here">
            <stage0 choices='{"Option1":1, "Option1":2}'>
                <text>text1</text> 
            </stage0>
            <stage1 next_stage="[3,4]">
                <text>text2</text> 
            </stage1>
            <stage3 npc_name="other_npc_name" ncp_condition='{"some_condition":false}' next_stage="[3, 4]">
                <text>text3</text>
            </stage3>
        </quest0>
    </npc>
</npcs>

但我在这方面遇到了麻烦:

<stage3 npc_name="other_npc_name" ncp_condition='{"some_condition":false}' next_stage="[3, 4]">

追溯:

Traceback (most recent call last):
  File "C:/.../test2.py", line 28, in <module>
    parse_file('quests.xml')
  File "C:/.../test2.py", line 15, in parse_file
    val = json.loads(val)
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

key="npc_name"val="other_npc_name" 时,它会在val = json.loads(val) 行中引发此错误。

这有什么问题? name="some string" 时没有报错,npc_name="some string" 时报错。

我注意到,如果我将 "other_npc_name" 更改为 '"other_npc_name"' 它不会抱怨,但这对我来说似乎有点 hackish

【问题讨论】:

    标签: python json xml xml-parsing


    【解决方案1】:

    JSON 是一种存储数据结构的方式 - 因此它只能解码所述数据结构。

    当您尝试让 JSON 解码如下内容时:

    other_npc_name

    JSON 无法将其与任何有效数据类型匹配。但是,如果这是用引号引起来的:

    “other_npc_name”

    JSON 将其识别为字符串(根据 JSON 规范,这是定义字符串的方式)。

    这就是你的脚本中发生的事情:

    import json
    print json.loads("other_npc_name") #throws error
    print json.loads('"other_npc_name"') #returns "other_npc_name" as a Unicode string
    

    因此,以这种方式包装字符串可能看起来很“hackish”,然而,这确实是 JSON 解码它的唯一方法。

    一个潜在的建议是,如果 XML 中的 npc_name 属性始终是字符串,则将其作为字符串提取出来,而不是尝试将其解码为 JSON 对象。

    【讨论】:

    • 哦,我明白了,我以为json会采用“other_npc_name”并尝试将其解码为str,现在很有意义。
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    相关资源
    最近更新 更多