python解析所有空值的Json

时间:2014-12-18 08:43:05

标签: 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的网络应用程序) 谢谢

1 个答案:

答案 0 :(得分:2)

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

#!/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