简体   繁体   English

如何从 Python 中的 JSON 中删除额外的方括号?

[英]How do I remove an extra square bracket from JSON in Python?

I have JSON of the following form:我有以下形式的 JSON:

{"blah":
 [
   [
     {"first":
     {"something":"that","something":"else","another":"thing","key":"value"}...[etc.]
     }
   ]
 ]
}

that I'm trying to parse in Python.我试图在 Python 中解析。 I've imported json (or simplejson, depending on what version of Python you're using) and everything goes pretty well until I get to this block:我已经导入了 json (或 simplejson,具体取决于您使用的 Python 的版本)并且一切顺利,直到我到达这个块:

for result in page['blah']:
  that = result['first']
  a_list.append(that)

which throws the error "TypeError: list indices must be integers, not str".这会引发错误“TypeError:列表索引必须是整数,而不是 str”。

I'm pretty sure this error is due to the extra pair of square-bracket that makes the JSON inside look like a list.我很确定这个错误是由于额外的一对方括号使 JSON 内部看起来像一个列表。

My question, assuming that's the case, is, How do I remove it and still have valid JSON to parse as dictionaries?假设是这种情况,我的问题是,如何删除它并且仍然有有效的 JSON 解析为字典?

Other workarounds welcome.欢迎其他解决方法。 If I need to supply more info, let me know.如果我需要提供更多信息,请告诉我。 Thanks!谢谢!

(Added the missing curly bracket and changed a couple of confusing terms--I was trying to come up with generic terms on the fly, sorry for any confusion.) (添加了缺少的大括号并更改了一些令人困惑的术语——我试图在飞行中提出通用术语,对于任何混淆感到抱歉。)

If there's always exactly one "extra" set of array brackets:如果总是有一组“额外”的数组括号:

for result in page['blah']:
    that = result[0]['this']
    list.append(that)

There is not need to remove the brackets from the JSON string.无需从 JSON 字符串中移除括号。 I think making sure to remove only the rights is not worth the effort.我认为确保只删除权利是不值得的。 Just figure out the right way to access the values you want.只需找出访问所需值的正确方法即可。

The "extra" brackets are not the only problem. “额外的”括号不是唯一的问题。 this is a property of an object which is the value of first . this是 object 的属性,它是first的值。 So to access this , you'd have to write所以要访问this ,你必须写

that = result[0]['first']['this']

Whether this always works or not depends on the left-out JSON data.这是否总是有效取决于遗漏的 JSON 数据。

First, you are right - your error is related to the incorrect use of the Python data types and JSON output.首先,您是对的 - 您的错误与 Python 数据类型和 JSON output 的错误使用有关。

Second, don't use list and all other Python reserved words when creating your variables.其次,在创建变量时不要使用list和所有其他 Python 保留字。

Finally, if you simply want to get all results for 'this' inner key, you can try using the following code:最后,如果您只是想获取'this'内键的所有结果,可以尝试使用以下代码:

data = {"blah":
 [
   [
     {"first":
     {"this":"that",
     "something":"else","another":"thing","key":"value"}}
   ]
 ]
}
outres = []
for k,v in data.items():#iterate over top dictionary('blah',....)
    for sv in v: # iterate through first list
        for tv in sv: # iterate through second list
            for fk,fv in tv.iteritems(): # iterate through each dicionary from second list
                if 'this' in fv:
                    outres.append(fv['this'])
print outres

Please note that my sample is based on your data sample - so if there is any additional levels in your data structure, or if any other rules should be applied, then the code should be modified.请注意,我的示例基于您的数据示例 - 因此,如果您的数据结构中有任何其他级别,或者应该应用任何其他规则,则应修改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM