首页 > 解决方案 > 递归 python-JSON 阅读器

问题描述

我在尝试创建递归函数时遇到问题,因此我可以使用多个嵌套字典和列表(有时在其他嵌套字典和列表中嵌套字典和列表)转换 json 文件。

基本上我试图在一个简单的 OrderedDict 中组织一个 JSON 文件,这样我就可以将它传递给 MongoDB 数据库

这是递归函数:

def JSON_Treating(self,json_data):

    headers = []
    data = []
    for key, value in json_data.iteritems():
        headers.append(key)
        try:
            if isinstance(value, (dict,list)):
                if isinstance(value, list) and isinstance(value[0], dict):

                    value = value[0]

                self.JSON_treating(value)

            data.append(value)
        except:
            data.append(value)
            Dict = OrderedDict(zip(headers,dados))

            self.JSON_treating(Dict)


    return Dict

这里的目标是,每次代码找到一个嵌套表时,它都会获取它的标题和值,并将标题附加到标题中,并将值附加到数据中,然后,当它完成时,代码将按顺序连接标题和值。

我的问题是,我做错了,看...代码没有得到所有嵌套的代码,或者代码根本不起作用。请帮忙谢谢!

编辑:这是输入 JSON 的示例

[
{
    "status": 0, 
    "payment_value": 0, 
    "date": "2018-07-28 12:18:00", 
    "Payment": [
        {
            "payment_general": 0, 
            "code": 1, 
            "total_value": 0, 
            "payment_form": "card"
        }
    ], 
    "id__": "", 
    "Product": [
        {
            "sku": "00000", 
            "ID_delivery": null, 
            "ammount": 1, 
            "unitary_value": 55.34, 
            "discount_name": null, 
            "delivery_form": null, 
            "discount_ammount": 0, 
            "delivery_charge": 20.34, 
            "taxes": 0, 
            "comission": null, 
            "id__discount": null
        }
    ], 
    "client": {
        "delivery": {
            "phone": [
                "1", 
                "2"
            ], 
            "fax": null, 
            "name": "A name here", 
            "state_tax": "free", 
            "address": {
                "reference": "a reference here", 
                "complement": "a complement here", 
                "block": "N123", 
                "city": "New York", 
                "road_name": "a road name", 
                "number": "413", 
                "postal_code": "123234", 
                "country": "US", 
                "State": "NY"
            }, 
            "email": "", 
            "document": ""
        }, 
        "taxation": {
            "phones": [
                "1", 
                "2"
            ], 
            "fax": null, 
            "type": "AN", 
            "nome": "a name here", 
            "state_demand": "A-B", 
            "birth_date": "1996-04-01", 
            "sex": "F-M", 
            "address": {
                "reference": "a reference here", 
                "complement": "a complement here", 
                "block": "N123", 
                "city": "New York", 
                "road_name": "a road name", 
                "number": "413", 
                "postal_code": "123234", 
                "country": "US", 
                "State": "NY"
            }, 
            "email": "a e mail ", 
            "document": "a document"
        }
    }, 
    "delivery_prevision": 10
}]

这就是我需要的样子:

{
"status": 0, 
"payment_value": 0, 
"date": "2018-07-28 12:18:00", 
"Payment": ,

"payment_general": 0, 
"code": 1, 
"total_value": 0, 
"payment_form": "card", 
"id__": "", 
"Product":, 
"NDE": "00000", 
"ID_delivery": null, 
"ammount": 1, 
"unitary_value": 55.34, 
"discount_name": null, 
"delivery_form": null, 
"discount_ammount": 0, 
"delivery_charge": 20.34, 
"taxes": 0, 
"comission": null, 
"id__discount": null,
"client": ,
"delivery": ,
"phone": "1" "2",
"fax": null, 
"name": "A name here", 
"state_tax": "free", 
"address": ,
"reference": "a reference here", 
"complement": "a complement here", 
"block": "N123", 
"city": "New York", 
"road_name": "a road name", 
"number": "413", 
"postal_code": "123234", 
"country": "US", 
"State": "NY",

"taxation": ,
"phones": "1",  "2"

"fax": null, 
"type": "AN", 
"nome": "a name here", 
"state_demand": "A-B", 
"birth_date": "1996-04-01", 
"sex": "F-M", 
"address": ,
"reference": 
"a reference here", 
"complement": "a complement here", 
"block": "N123", 
"city": "New York", 
"road_name": "a road name", 
"number": "413", 
"postal_code": "123234", 
"country": "US", 
"State": "NY",
"email": "a e mail ", 
"document": "a document",
"delivery_prevision": 10
}

标签: pythonjsonrecursionpymongo

解决方案


这对你有用吗?

class UnknownClassYouNeverShowed(object):
    def JSON_Treating(self, json_data):
        flat_dict = {}
        if isinstance(json_data, list):
            for item in json_data:
                if isinstance(item, (list, dict)):
                    flat_dict.update(self.JSON_Treating(item))
            return flat_dict

        for key, value in json_data.iteritems():
            if isinstance(value, (list, dict)):
                flat_dict.update(self.JSON_Treating(value))
            else:
                flat_dict[key] = value
        return flat_dict

如果你真的只有 json 字符串,加载它并将其提供给函数使用:import json; data = json.loads(some_json_string).. 你明白了。


测试我得到这个:

import pprint
unknown = UnknownClassYouNeverShowed()
pprint.pprint(unknown.JSON_Treating(data))

输出:

{'ID_delivery': None,
 'State': 'NY',
 'ammount': 1,
 'birth_date': '1996-04-01',
 'block': 'N123',
 'city': 'New York',
 'code': 1,
 'comission': None,
 'complement': 'a complement here',
 'country': 'US',
 'date': '2018-07-28 12:18:00',
 'delivery_charge': 20.34,
 'delivery_form': None,
 'delivery_prevision': 10,
 'discount_ammount': 0,
 'discount_name': None,
 'document': 'a document',
 'email': 'a e mail ',
 'fax': None,
 'id__': '',
 'id__discount': None,
 'name': 'A name here',
 'nome': 'a name here',
 'number': '413',
 'payment_form': 'card',
 'payment_general': 0,
 'payment_value': 0,
 'postal_code': '123234',
 'reference': 'a reference here',
 'road_name': 'a road name',
 'sex': 'F-M',
 'sku': '00000',
 'state_demand': 'A-B',
 'state_tax': 'free',
 'status': 0,
 'taxes': 0,
 'total_value': 0,
 'type': 'AN',
 'unitary_value': 55.34}

推荐阅读