python - 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!
解决方案
您可以遍历列表以获得所需的结果。
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']}]}
推荐阅读
- arrays - 在循环外访问数组
- shell - 从 csv 文件转换日期格式时出现“无效日期”错误消息?-壳
- python - 如何在我的 PyQt5 Qwidget 上显示 matplotlib
- caching - 用于 dotnet lambdas 的 AWS SSM 参数存储的缓存解决方案
- vue.js - 在 VueJS 2 组件模板外使用带有 dom 元素的 ref 属性
- nlp - 谓词-参数结构(spo)和RDF三元组之间的区别
- java - spring-data-jdbc 中的参数化顺序
- postgresql - 并发查询的 MVCC 快照限制
- typescript - 在 gatsby 配置中导入图像失败
- java - java调用另一个类的方法从同一个包中打印