python - Python解析Json所有空值

标签 python json error-handling web2py

在web2py服务器上使用python我有以下问题。
我如何循环通过json来查找所有具有空值(或空字符串)的键并收集这些键以报告缺少的内容:

这是我的json示例。

 {
"version" : 1,
"general" : {
    "scriptFrom" : "",
    "scriptTo" : "1.1.2014",
    "scriptComment" : "dada"
},
"nbworkersDays" : [{
        "days" : ["1", "2"],
        "data" : [{
                "nbWorkersFrom" : 2,
                "nbWorkersTo" : null,
                "timeFrom" : "12:00",
                "timeTo" : ""
            }
        ,{
            "nbWorkersFrom" : 2,
            "nbWorkersTo" : 7,
            "timeFrom" : "9:00",
            "timeTo" : "14:00"
        }
    ]
    }
]}

我当时想检索包含所有键的列表,如果嵌套的话还比第一级要多。第二级。
missingData = [scriptFrom,nbworkersDays.nbWorkersTo,nbworkersDays.timeTo]

有关如何解决此问题的任何建议,或者您如何收集所有错误以报告给客户
(我有一个使用web2py的网络应用程序)
谢谢

最佳答案

您可以使用递归函数来迭代复杂对象的值,同时记住您所处的路径(以进行报告):

#!/usr/bin/env python

# used to parse the json text
import json
with open('json.txt', 'r') as f:
    d = json.load(f)
# define list of what your consider as "missing"
missings = [None, ""]

# recursive function to collect missing paths and alter the aggregator list
# make sure to add cases if needed
def aggregate_missing_paths(aggregator, path, item):
    if isinstance(item, list):
        # check all list items
        map(lambda x: aggregate_missing_paths(aggregator, path, x), item)
    if isinstance(item, dict):
        # check all dict items
        map(lambda kv: aggregate_missing_paths(aggregator, path + '.' + kv[0], kv[1]), item.iteritems())
    if item in missings:
        # alter list to cotain path to missing
        aggregator.append(path)

aggregator = []
aggregate_missing_paths(aggregator, 'root', d)
print aggregator

编辑:

我使用递归生成器添加了一个没有聚合器的版本:
#!/usr/bin/env python

import json
with open('json.txt', 'r') as f:
    d = json.load(f)
missings = [None, ""]
def generate_missing_paths(path, item):
    if isinstance(item, list):
        for v in item:
            for current_path in generate_missing_paths(path, v):
                yield current_path
    if isinstance(item, dict):
        for k, v in item.iteritems():
            for current_path in generate_missing_paths(path + '.' + k, v):
                yield current_path
    if item in missings:
        yield path

for path in generate_missing_paths('root', d):
    print path

关于python - Python解析Json所有空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27542348/

相关文章:

c# - 如果数据库中没有这样的行,我将返回什么?

Python SequenceMatcher 开销 - 100% 的 CPU 使用率和非常缓慢的处理

python - dreload() 和 autoreload 之间的关系/区别

python - pjsua - 禁止 403(错误的身份验证)

javascript - 如何通过php和ajax将html添加到返回的json对象

javascript - 是否可以向现有 JSON 数据添加新属性?

python - Flask View 引发 TypeError 得到意外的关键字参数

json - 如何成功将 HttpClient 的 JSON 响应内容绑定(bind)到模型并从后端 REST API 以 JSON 形式返回该模型?

c - 在 Ubuntu 中出现段错误(核心转储)错误

error-handling - lua 递归 repl 错误?