Преобразовать строку в список списков диктов Python - PullRequest
2 голосов
/ 30 мая 2019

Я новичок в питоне. У меня есть строка, которая взята из моей базы данных sqlite. Я хочу преобразовать строку в list of list of dicts. Я пробовал библиотеку ast и json, но она не работает.

Вот строка:

a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'

Вот код, который я попробовал:

import ast
import json
a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'
a = a.replace("[[","[").replace("]]","]")
print(a)

# using json library- fails
# jdata = json.loads(a)
# for d in jdata:
#     for key, value in d.iteritems():
#         print (key, value)

#using ast library - it also fails
# res = [ast.literal_eval(x) for x in a]

Я попробовал эту ссылку конвертировать строку в dict и конвертировать str в список списка

Но в моем случае у меня есть list of list of dicts в форме строки. Как сделать это возможным.

Я хочу то же самое, что и вывод, но он должен быть в списке списка диктов.

Требуемый вывод:

[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]

Ответы [ 3 ]

5 голосов
/ 30 мая 2019

Это должно работать.

import ast
a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'

print(ast.literal_eval(a.strip('"')))

Выход:

[[{'dbname': 'smackcoders',
   'host': 'localhost',
   'id': 'mysql1',
   'limit_count': 5,
   'password': 'root',
   'plugin': 'mysql',
   'plugin_type': 'input',
   'tbname': 'agg_csv',
   'user': 'root'},
  {'action': 'count',
   'field': 'state',
   'field_name': 'count_result',
   'id': 'metrics',
   'input_from': 'mysql1',
   'plugin': 'metrics',
   'plugin_type': 'filter',
   'send_data_immediately': True,
   'value': 'kerala'},
  {'doc_typ': 'sm23',
   'id': 'elastic_search',
   'ind': 'neww10',
   'input_from': 'metrics',
   'plugin': 'elastic',
   'plugin_type': 'output'}]]
4 голосов
/ 30 мая 2019

Попробуйте это.

a = '"[[{"plugin_type":"input","plugin":"mysql","dbname":"smackcoders","user":"root","password":"root","tbname":"agg_csv","host":"localhost","id":"mysql1","limit_count":5},{"plugin_type":"filter","plugin":"metrics","input_from":"mysql1","id":"metrics","field_name":"count_result", "field":"state","value":"kerala","action":"count","send_data_immediately":True},{"plugin_type":"output","plugin":"elastic","id":"elastic_search","input_from":"metrics","ind":"neww10","doc_typ":"sm23"}]]"'

a=a.strip('"')
a=eval(a)
4 голосов
/ 30 мая 2019

Вы можете использовать ast.literal_eval.Вы просто должны убедиться, что строка, которую вы вводите, может быть проанализирована.В этом случае достаточно удалить начальные и конечные кавычки:

from ast import literal_eval
literal_eval(a[1:-1]) # or strip('"') as in rakesh' answer


[[{'dbname': 'smackcoders',
   'host': 'localhost',
   'id': 'mysql1',
   'limit_count': 5,
   'password': 'root',
   'plugin': 'mysql',
   'plugin_type': 'input',
   'tbname': 'agg_csv',
   'user': 'root'},
  {'action': 'count',
   'field': 'state',
   'field_name': 'count_result',
  ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...