我有一个JSON对象数组,如下所示。如何解析数组中的每个JSON对象?
例如,我想解析{"occurrences":"1","post_title":"Test 5","ID":"16"}
并将其作为正文发送到API。
[
{
"occurrences": "1",
"post_title": "Test 5",
"ID": "16"
},
{
"occurrences": "1",
"post_title": "Test 6",
"ID": "19"
},
{
"occurrences": "1",
"post_title": "xyz,abc",
"ID": "21"
}
]
答案 0 :(得分:0)
在to_be_searched
变量中添加搜索到的参数。
条件是否与所有对象一一对应检查。
import json
result = '[{"occurrences":"1","post_title":"Test 5","ID":"16"},{"occurrences":"1","post_title":"Test 6","ID":"19"},{"occurrences":"1","post_title":"xyz,abc","ID":"21"}]'
to_be_searched = {"occurrences": "1", "post_title": "Test 5", "ID": "16"}
result_arr = json.loads(result)
for res in result_arr:
if res["occurrences"] == to_be_searched["occurrences"] and res["post_title"] == to_be_searched["post_title"] and \
res["ID"] == to_be_searched["ID"]:
print(res)
如果在执行上述AttributeError: module 'json' has no attribute 'loads'
之类的代码时遇到任何问题,也可以使用simplejson模块。
通过在终端上执行以下命令来安装simplejson模块
pip install simplejson
对于python3
pip3 install simplejson
只需将上面代码中的第一行更改为
import simplejson as json