user3908838
user3908838

Reputation: 9

python list of string converts to list of dict

I'm trying to convert list of string like this

['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']

to list of dict like this

[{"What is the purpose of a noun?":"To name something or someone."}, {"What       is the purpose of a verb?":"To show action"}]  

This is what the original string like in txt file

{"What is the purpose of a noun?":"To name something or someone."}
{"What is the purpose of a verb?":"To show action in a sentence."}  

json module doesn't work

a = []
with open("proans.txt",'r') as proans:
    #transform string in the txt file into list of string by \n
    pa = proans.read().split('\n')
    #iterate through the list of string, convert string to dict and put them                           
    #into a list
    for i in range(len(pa)):
        json_acceptable_string = pa[i].replace("\"", "'")
        ret_dict = json.loads(json_acceptable_string)
        a.append(ret_dict)  

I got error like this

ValueError: Expecting property name: line 1 column 2 (char 1)  

How do I do to transform this type of list of string to list of dict? Thanks

Upvotes: 1

Views: 181

Answers (1)

jayelm
jayelm

Reputation: 7678

Get rid of the replace line: json_acceptable_string = .... There's no need to escape quotations.

>>> lst = ['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']
>>> import json
>>> [json.loads(el) for el in lst]
[{u'What is the purpose of a noun?': u'To name something or someone.'}, {u'What is the purpose of a verb?': u'To show action'}]
>>> [json.loads(el.replace("\"", "'")) for el in lst]
Traceback (most recent call last):
  ...
ValueError: Expecting property name: line 1 column 2 (char 1)

Example similar to the original code with a StringIO object:

>>> proans = StringIO.StringIO("""{"What is the purpose of a noun?":"To name something or someone."}
... {"What is the purpose of a verb?":"To show action in a sentence."}""")
>>> pa = proans.read().split('\n')
>>> proans
['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action in a sentence."}']
>>> for i in range(len(pa)):
...     print json.loads(pa[i])
...
{u'What is the purpose of a noun?': u'To name something or someone.'}
{u'What is the purpose of a verb?': u'To show action in a sentence.'}

Upvotes: 1

Related Questions