如何在Python中将列表数据转换为格式化的json

时间:2018-08-09 09:35:38

标签: python json python-2.7 formatting

列表数据如下:

[
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0",
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Cross Site Scripting--->1.0",
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0",
    "message: // System.out.println(\"\" + bean.getBlockId());-->0.507092552837",
    "category: Denial of Service--->1.0",
    "message: * System.out.println(objects[0]); Long l =--->0.507092552837",
    "category: Cross Site Scripting--->1.0"
]

我希望将上面的列表数据转换为应如下所示的json:

[
   {
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0"
   },
   {
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Cross Site Scripting--->1.0"
   },
   {
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0"
   },
   {
    "message: // System.out.println(\"\" + bean.getBlockId());-->0.507092552837",
    "category: Denial of Service--->1.0"
   },
   {
    "message: * System.out.println(objects[0]); Long l =--->0.507092552837",
    "category: Cross Site Scripting--->1.0"
   }
]

注意:我已经尝试过json.dumps(),但它确实可行!

1 个答案:

答案 0 :(得分:1)

使用列表切片。

例如:

lst = [
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0",
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Cross Site Scripting--->1.0",
    "message: // System.out.println(\"resultMap -- \"+resultMap);--->1.0",
    "category: Poor Logging Practice--->1.0",
    "message: // System.out.println(\"\" + bean.getBlockId());-->0.507092552837",
    "category: Denial of Service--->1.0",
    "message: * System.out.println(objects[0]); Long l =--->0.507092552837",
    "category: Cross Site Scripting--->1.0"
]

res = []
for i in range(0, len(lst), 2):       
    message, category = lst[i:i+2]
    res.append({"message": message.lstrip("message:"), "category": category.lstrip("category:")})
print(res)

输出:

[{'category': ' Poor Logging Practice--->1.0',
  'message': ' // System.out.println("resultMap -- "+resultMap);--->1.0'},
 {'category': ' Cross Site Scripting--->1.0',
  'message': ' // System.out.println("resultMap -- "+resultMap);--->1.0'},
 {'category': ' Poor Logging Practice--->1.0',
  'message': ' // System.out.println("resultMap -- "+resultMap);--->1.0'},
 {'category': ' Denial of Service--->1.0',
  'message': ' // System.out.println("" + bean.getBlockId());-->0.507092552837'},
 {'category': ' Cross Site Scripting--->1.0',
  'message': ' * System.out.println(objects[0]); Long l =--->0.507092552837'}]