Alternate way to read a file as json using python

127 views Asked by At

I have a file that contains information similar to the example shown below. I would like to know if there is a way to read this file using python and use it as json. I am aware of how to open it and process the text but is there another way?

Example:

key={{name='foo', etc..},{},{},{}}
2

There are 2 answers

1
gbriones.gdl On

If you want your content to be treated as json you need to have a valid json syntax:

{"key":[{"name": "foo"},{},{},{}]}

Then you can use json library to convert it to a dictionary:

>>> import json
>>> json.loads('{"key":[{"name": "foo"},{},{},{}]}')
{u'key': [{u'name': u'foo'}, {}, {}, {}]}

Additionally, if your file content cannot be changed to a correct json syntax, then you will need to develop a parser for your specific case.

0
crisis On

After searching a few different languages I was able to determine that the data struct was a Lua container. I found a simple lua-python parser currently available here github.com/SirAnthony/slpp and I was able to parse(decode) the lua data structure. Below is an example of parsing a lua container with slpp.py I hope this helps anyone with a similar problem.

>>> from slpp import slpp as lua
>>> data = lua.decode('{ array = { 65, 23, 5 }, dict = { string = "value",    array = { 3, 6, 4}, mixed = { 43, 54.3, false, string = "value", 9 } } }')
>>> print data

{'array': [65, 23, 5], 'dict': {'mixed': {0: 43, 1: 54.33, 2: False, 4: 9, 'string': 'value'}, 'array': [3, 6, 4], 'string': 'value'}}