简体   繁体   English

使用 python 将文件读取为 json 的另一种方法

[英]Alternate way to read a file as json using python

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.我想知道是否有办法使用 python 读取此文件并将其用作 json。 I am aware of how to open it and process the text but is there another way?我知道如何打开它并处理文本,但还有其他方法吗?

Example:例子:

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

If you want your content to be treated as json you need to have a valid json syntax:如果您希望您的内容被视为 json,您需要有一个有效的 json 语法:

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

Then you can use json library to convert it to a dictionary:然后您可以使用 json 库将其转换为字典:

>>> 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.此外,如果您的文件内容无法更改为正确的 json 语法,那么您将需要针对您的特定情况开发解析器。

After searching a few different languages I was able to determine that the data struct was a Lua container.在搜索了几种不同的语言后,我能够确定数据结构是一个 Lua 容器。 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.我在 github.com/SirAnthony/slpp 上找到了一个当前可用的简单 lua-python 解析器,我能够解析(解码)lua 数据结构。 Below is an example of parsing a lua container with slpp.py I hope this helps anyone with a similar problem.以下是使用 slpp.py 解析 lua 容器的示例,我希望这可以帮助遇到类似问题的任何人。

>>> 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'}} {'array': [65, 23, 5], 'dict': {'mixed': {0: 43, 1: 54.33, 2: False, 4: 9, 'string': 'value'}, 'array ': [3, 6, 4], '字符串': '值'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM