【问题标题】:python json.loads / json.load truncates nested json objects?python json.loads / json.load 截断嵌套的 json 对象?
【发布时间】:2013-07-09 01:06:10
【问题描述】:

给出以下代码:

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" 
            }, 

【问题讨论】:

    标签: python json


    【解决方案1】:

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

    如果您需要多个值,请将数据格式更改为一个键与一个数组值:

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

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

    【讨论】:

    • duuuuuuuuuuuhhhhhhhhhhhhhhhhhhh
    • 实际上,我做不到。 “属性”值是我需要的元数据。我只需要切换键和值,因此“属性”:“状态 ID”将变为“状态 ID”:“属性”。所有都是属性的事实是偶然的。它基本上是一个可能值的枚举
    • 它实际上是有效的,但几乎不能用于任何语言。 "The names within an object SHOULD be unique." §2.2
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2015-08-23
      • 2011-07-06
      • 2017-10-02
      • 1970-01-01
      相关资源
      最近更新 更多