使用 json 解析 XML 引发 ValueError

Parsing XML using json raises ValueError

我正在尝试使用 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"' 它不会抱怨,但这对我来说似乎有点老套

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 对象.