首页 > 解决方案 > Python list formatting with JSON

问题描述

I'm a newbie in Python trying to turn information from an Excel file into JSON output.

I'm trying to parse this Python list:

value = ['Position: Backstab, Gouge,', 'SumPosition: DoubleParse, Pineapple']

into this JSON format:

"value": [
      {
        "Position": [
          "Backstab, Gouge,"
        ]
      },
      {
        "SumPosition": [
          "DoubleParse, Pineapple"
        ]
      }
    ]

Please note:

This list was previously a string:

value = 'Position: Backstab, Gouge, SumPosition: DoubleParse, Pineapple'

Which I turned into a list by using re.split().

I've already turned the string into a list by using re.split, but I still can't turn the inside of the string into a dict, and the value from the dict into a list.

Is that even possible? Is it the case to format the list/string with JSON or previously prepare the string itself so it can receive the json.dump method?

Thanks in advance!

标签: pythonjson

解决方案


您可以遍历列表以获得所需的结果。

d = {'value': []}
for val in value:
    k, v = val.split(':')
    tmp = {k.strip() : [v.strip()]}
    d['value'].append(tmp)

print(d)

{'value': [{'Position': ['Backstab, Gouge,']},
  {'SumPosition': ['DoubleParse, Pineapple']}]}

推荐阅读