简体   繁体   English

将一组字符串转换为python中的json

[英]converting a set of strings to a json in python

I am currently working on setting up a flask server for my front end. 我目前正在为前端设置Flask服务器。 The request I get is in the form the following JSON object: 我收到的请求采用以下JSON对象的形式:

InputJson = {"text":"Field1:A|Field2:B|Field3:C","format":"Reader"}

I would like to convert the text field to a proper JSON: 我想将文本字段转换为适当的JSON:

OutputJson = {"Field1":"A","Field2":"B","Field3":"C"}

What I did so far: 到目前为止,我做了什么:
I first replaced the pipes using string.replace in python. 我首先在python中使用string.replace替换了管道。 However, I end up with a plain string which I am not able to convert to json. 但是,我最终得到了一个普通字符串,无法将其转换为json。

I have tried using json.loads on the cleaned string (I replaced the | with , . 我已经尝试使用json.loads清除后的字符串(我更换了|,

Any help here would be great. 这里的任何帮助将是巨大的。

You can split your string on "|", then split each part on ":", feeding the pairs into a dict: 您可以在“ |”上分割字符串,然后在“:”上分割每个部分,然后将对放入字典中:

output = dict( keyvalue.split(':') for keyvalue in orig_value.split('|') )

You don't need to use any json-parsing tools for that, because the format of the string you're parsing has nothing to do with json formatting. 您不需要为此使用任何json解析工具,因为您解析的字符串的格式与json格式无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM