如何使用python将包含键值对的嵌套列表转换为json格式

时间:2019-01-23 19:20:55

标签: python json

我有['key','value']格式列表,其中还包含子列表。如何在python

中将嵌套列表转换为JSON格式
[[' key ', ' 1542633482511430199'
 ],
 ['value=>>>BasicData',
  [['isConfirmAndOrder', '0'],['brmRequestId', 'BR-2018-0000124'],
  ['requestType','batch'],['projectId', 'PRJ-2018-0000477'],
  ['createdOn', 'Mon Nov 19 18:48:02 IST 2018']]
 ],    
 ['createdBy=>>>BasicData',
  [['userId', '999996279'],    ['email', 'ITEST275@ITS.JNJ.com'],
  ['firstName', 'Iris'],    ['lastName', 'TEST275'],
  ['ntId', 'itest275'],    ['region', 'NA'],
  [' LastAccessTime ', ' 1542639905785 ']]
 ]
]

格式为

{
"key": "1542633482511430199",
"value=>>>BasicData": {
    "isConfirmAndOrder": "0",
    "brmRequestId": "BR-2018-0000124"
        .
},
"createdBy=>>>BasicData": {
    "userId": "999996279",
    "email": "ITEST275@ITS.JNJ.com"
        .
 }
        .
 }

大数据的实际格式为:

[
 [
  ['key11','value11']
  ['key12',['key13','value13']]
  ['key14',['key15','value15']]
 ]
[
  ['key21','value21']
  ['key22',['key23','value23']]
  ['key24',['key25','value25']]
 ]
]

2 个答案:

答案 0 :(得分:1)

您可以为此编写一个简单的递归函数:

def to_dict_recursive(x):
    d = {}
    for key, value in x:
        if isinstance(value, list):
            value = to_dict_recursive(value)
        else:
            value = value.strip()  # get rid of unnecessary whitespace
        d[key.strip()] = value
    return d

to_dict_recursive(x)
# {'createdBy=>>>BasicData': {'displayName': 'Iris TEST275',
#   'email': 'ITEST275@ITS.JNJ.com',
#   'firstName': 'Iris',
#   'lastName': 'TEST275',
#   'ntId': 'itest275',
#   'region': 'NA',
#   'roles': '[0]CG510_DHF_AP_Role',
#   'userId': '999996279'},
#  'formulaDetails=>>>BasicData': {'CreationTime': '1542633482512',
#   'LastAccessTime': '1542639905785',
#   'batchSizeUnits': 'kg<<<<<<',
#   'hitCount': '1',
#   'version': '1'},
#  'key': '1542633482511430199',
#  'value=>>>BasicData': {'brmRequestId': 'BR-2018-0000124',
#   'createdMonth': 'Nov',
#   'createdOn': 'Mon Nov 19 18:48:02 IST 2018',
#   'department': 'Global Packaging',
#   'gxp': '1',
#   'id': '1542633482511430199',
#   'isConfirmAndOrder': '0',
#   'isFilling': 'false',
#   'projectId': 'PRJ-2018-0000477',
#   'projectName': 'Automation_Product_By_Admin',
#   'requestType': 'batch',
#   'status': 'New',
#   'statusDescription': 'Batch request created',
#   'updatedOn': 'Mon Nov 19 18:48:02 IST 2018'}}

(我在Python 3.6中运行了此命令,因此字典表示形式中键的顺序与插入顺序不同。在Python 3.7+中,此顺序将有所不同。)

您甚至可以将其理解为字典理解:

def to_dict_recursive(x):
    return {key.strip(): to_dict_recursive(value) if isinstance(value, list)
                         else value.strip
            for key, value in x}

由于对象中的某些元素显然不是键和值的两元素列表,因此可以添加一个简单的防范措施:

def to_dict_recursive(x):
    d = {}
    try:
        for key, value in x:
            if isinstance(value, list):
                value = to_dict_recursive(value)
            else:
                value = value.strip()
            d[key.strip()] = value
    except ValueError:
        return x
    return d

x = [[' key ', ' 1542633482511430199'],
 ["test", ["a", "b", "c"]]
]
to_dict_recursive(x)
# {'key': '1542633482511430199', 'test': ['a', 'b', 'c']}

答案 1 :(得分:0)

请注意,如果mylist是键值对列表,那么dict(mylist)只会返回其字典版本。棘手的部分是遍历这些嵌套列表,以用字典替换它们。这是执行此操作的递归函数:

# Where <kv> is your giant list-of-lists.
def kv_to_dict(kv):
    if isinstance(kv, list):
        kv = dict(kv)
    for k in kv:
        if isinstance(kv[k], list):
            kv[k] = kv_to_dict(kv[k])
    return kv

newdict = kv_to_dict(kvpairs)

一旦您将内容转换为字典,就可以使用json.dumps()将其格式化为JSON:

import json
as_json = json.dumps(newdict, indent=4)
print(as_json)

我知道您尝试过类似的操作并遇到错误。您确定数据中的所有列表都是真正的键值对,而不是例如3个字符串的列表吗?