flowerflower
flowerflower

Reputation: 337

Convert a list from type str to type list

It must be simple, but I don't know it:

I've got a file.json with this content

[{u'key': u'value1'},{u'key': u'value2'}]

and imported it as data

with open(file.json) as fd:
        data = fd.read()

I'm quite happy that this works

>>> print (data)
[{u'key': u'value1'},{u'key': u'value2'}]

But unfortunately data is now converted as str

>>> print(type(data))
<type 'str'>

So I can't use data to do things like deleting items.

How do I convert data to a normal list of dicts? (<type 'list'>)

Upvotes: 0

Views: 224

Answers (2)

omri_saadon
omri_saadon

Reputation: 10631

Very simple with json library.

import json
obj = json.loads(json_string) 

Deserialize json_string (json_string is str or unicode instance containing a JSON document) to a Python object (dixt in our case).

EDIT:

As Stefan mention, this is not a valid json(it looks like a list) and therefore you can see Tim's answer.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

If you use the file method .read(), you always get a string. You'd have to parse it yourself, but fortunately, Python has a json module that does all the parsing for you. It even reads the file:

import json
with open(file.json) as fd:
    data = json.load(fd)

But, as Stefan has pointed out, your file isn't valid JSON - it rather looks like the repr() output of a Python object. In that case, it's nearly as simple:

import ast
with open(file.json) as fd:
    data = ast.literal_eval(fd.read())

Upvotes: 3

Related Questions