Python将字符串解析为字典

时间:2018-12-26 13:16:55

标签: python json string parsing dictionary

我有以下字符串:

"[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

我想将其解析为dict / json。 最好的方法是什么?

3 个答案:

答案 0 :(得分:4)

您可以使用ast.literal_eval评估字符串并获取Python对象(如果语法正确)。 Using this is safer than using eval

import ast

s = "[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

l = ast.literal_eval(s)
d = dict(l)
{'Categories': [['180972'],
  ['180800'],
  ['16228'],
  ['32733'],
  ['32789'],
  ['32833'],
  ['325137'],
  ['32839'],
  ['25329'],
  ['42605'],
  ['428240849'],
  ['5101'],
  ['568'],
  ['570716'],
  ['57116'],
  ['57080545404'],
  ['57083134076']],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']}

如果您还想摆脱内部列表,请使用the other answer,而不是仅在对象上调用dict

答案 1 :(得分:0)

尝试将其转换为字典:

data= "[['Categories', [['180972'], ['180800'], ['16228'], ['32733'], ['32789'], ['32833'], ['325137'], ['32839'], ['25329'], ['42605'], ['428240849'], ['5101'], ['568'], ['570716'], ['57116'], ['57080545404'], ['57083134076']]], ['Tags', ['Stock', 'Color', 'Fam', 'Dress','Maxi']], ['Type', ['Luxary']], ['Vendor', ['AAA']]]"

data = eval(data)

d={}
for i in data:
    d[i[0]] = [x for x, in i[1]] if isinstance(i[1][0], list) else i[1]

输出将是:

{'Categories': 
  ['180972',
   '180800',
   '16228',
   '32733',
   '32789',
   '32833',
   '325137',
   '32839',
   '25329',
   '42605',
   '428240849',
   '5101',
   '568',
   '570716',
   '57116',
   '57080545404',
   '57083134076'],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']
}

答案 2 :(得分:0)

怎么样

>>> import itertools
>>> import ast
>>> import pprint
>>> i = ast.literal_eval(s)
>>> d = {k[0]:list(itertools.chain(*k[1])) if isinstance(k[1][0], list) else list(k[1]) for k in i}
>>> pprint.pprint(d)
{'Categories': ['180972',
                '180800',
                '16228',
                '32733',
                '32789',
                '32833',
                '325137',
                '32839',
                '25329',
                '42605',
                '428240849',
                '5101',
                '568',
                '570716',
                '57116',
                '57080545404',
                '57083134076'],
 'Tags': ['Stock', 'Color', 'Fam', 'Dress', 'Maxi'],
 'Type': ['Luxary'],
 'Vendor': ['AAA']}