Строка до JSON в Python - PullRequest
       17

Строка до JSON в Python

0 голосов
/ 20 июня 2020

У меня есть образец строки, мне нужно преобразовать строку в формат JSON. Я пробовал n разными способами, но не смог этого добиться. Было бы здорово, если бы кто-нибудь помог мне построить это. позиция строки образца продолжает меняться, нам нужно выбрать данные на основе присутствующего ключа 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"
}

1 Ответ

1 голос
/ 20 июня 2020

Я не хочу использовать регулярное выражение, просто строковый метод

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'}
...