首页 > 解决方案 > Python中的字符串到JSON

问题描述

我有一个示例字符串,我需要将字符串转换为 JSON 格式。我尝试了多种方法但无法实现,如果有人帮助我构建它,那听起来真的很棒。示例字符串位置不断变化,我们需要根据存在的 JSON 键选择数据。

示例字符串:

sample ="The following are the graphical (non-control) characters defined by
ISO 8859-1 (1987).  DESCRIPTION :  in words aren't all that helpful,
but they're the best we can do in text.  A graphics file illustrating
the character set should be available from the same archive as this
file.RESULT :success INTERPRETATION : ISO 8859-1 (1987).CREATED_BY:Questy.CREATED_ON:29/07/1963"

所需的 JSON 输出

{
   "DESCRIPTION":" in words aren't all that helpful but they're the best we can do in text.   A graphics file illustrating the character set should be available from the same archive as thisfile",
   "RESULT":"success",
   "INTERPRETATION":" ISO 8859-1 (1987)",
   "CREATED_BY":"Questy",
   "CREATED_ON":"29/07/1963"
}

标签: pythonpython-3.xpython-2.7

解决方案


我不想使用正则表达式,只是字符串方法

sample = ("The following are the graphical (non-control) characters defined "
          "by ISO 8859-1 (1987).  DESCRIPTION :  in words aren't all that "
          "helpful, but they're the best we can do in text.  A graphics file "
          "illustrating the character set should be available from the same "
          "archive as this file.RESULT :success INTERPRETATION : ISO 8859-1 "
          "(1987).CREATED_BY: Questy.CREATED_ON:29/07/1963")

sample = sample.replace('.', '. ').replace('.  ', '. ')

lst = list(map(str.strip, sample.split(':')))

result = {}

for i in range(len(lst)-1):
    if i < len(lst)-2:
        result[lst[i].split()[-1]] = ' '.join(lst[i+1].split()[:-1]).strip('.')
    else:
        result[lst[i].split()[-1]] = lst[i+1].strip('.')
>>> result
{'CREATED_BY': 'Questy',
 'CREATED_ON': '29/07/1963',
 'DESCRIPTION': "in words aren't all that helpful, but they're the best we can "
                'do in text. A graphics file illustrating the character set '
                'should be available from the same archive as this file',
 'INTERPRETATION': 'ISO 8859-1 (1987)',
 'RESULT': 'success'}

推荐阅读