0

给出以下代码:

import json 
foo = '{"root":"cfb-score","children":{"gamecode":{"attribute":"global-id"},"gamestate":{"attribute":"status-id","attribute":"status","attribute":"quarter","attribute":"minutes","attribute":"seconds","attribute":"team-possession-id","attribute":"yards-from-goal","attribute":"down","attribute":"distance","attribute":"segment-number","attribute":"active-state"},"gametype":{"attribute":"type","attribute":"detail"},"stadium":{"attribute":"name","attribute":"city","attribute":"state"},"visiting-team:team-name":{"attribute":"alias"},"visiting-team:team-code":{"attribute":"global-id"},"visiting-team:team-rank":{"attribute":"rank"}}}'

bar = json.loads(foo)
print json.dumps(bar)

在使用 json.loads 或 json.load 时,所有最低级别的“子级”都被截断(或者更有可能被覆盖),除了最后一个。为什么?json 格式正确,可以在此处验证:http: //json.parser.online.fr/

一大块输入:

"children" : {
        "gamecode" : {
            "attribute" :  "global-id"
        },
        "gamestate" : {
            "attribute" : "status-id", 
            "attribute" : "status", 
            "attribute" : "quarter", 
            "attribute" : "minutes", 
            "attribute" : "seconds", 
            "attribute" : "team-possession-id", 
            "attribute" : "yards-from-goal", 
            "attribute" : "down", 
            "attribute" : "distance", 
            "attribute" : "segment-number", 
            "attribute" : "active-state" 
        }, 

转向这块输出:

"children" : {
            "gamecode" : {
                "attribute" :  "global-id"
            },
            "gamestate" : {
                "attribute" : "active-state" 
            }, 
4

2 回答 2

1

JSON 不关心对象的键,但 json.load 和 json.loads 使用此转换表转换为 Python 对象。JSON 对象被转换成 python 字典,这意味着你不能有重复的键。

于 2013-07-10T22:17:20.117 回答
1

JSON 格式正确(即语法上有效)但语义上无效。Python dict 和 JS 对象中不能有多个具有相同值的键。如果您在链接到的页面上验证该输入,您会看到“JS eval”窗格也显示“截断”数据。

如果您想要多个值,请将数据的格式更改为具有一个带有数组值的键:

"gamestate" : {
            "attributes": ["status-id", "status", "quarter", ...]
        }, 

(或者,根据整体数据的情况,您可以将gamestate键直接链接到数组,而不是在键下嵌套另一层attribute。)

于 2013-07-10T22:17:22.200 回答