python json.loads / json.load截断嵌套的json对象?

时间:2013-07-10 22:15:18

标签: python json

给出以下代码:

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时的最后一个,所有最低级别的'children'都被截断(或者可能更有可能被覆盖)。为什么? 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" 
            }, 

2 个答案:

答案 0 :(得分:1)

JSON不关心对象的键,但json.load和json.loads使用this conversion table转换为Python对象。 JSON对象被转换为python dict,这意味着你不能有重复的键。

答案 1 :(得分:1)

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

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

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

(或者,根据整体数据的含义,你可以让gamestate键直接链接到数组,而不是在attribute键下有另一层嵌套。)