跳转到主要内容

轻松处理字符串中包含的JSON。包括一个命令行工具,用于格式化输入中的JSON,类似于内置的json.tool。

项目描述

jsonfinder 允许您使用简单的迭代器在字符串中查找和提取嵌入的JSON对象和数组。例如

>>> s = 'jack [1,2,3] john'
>>> for start, end, obj in jsonfinder(s):
...     print start, ':', end
...     if obj is None:
...         print 'String:', repr(s[start:end])
...     else:
...         print 'List of length', len(obj)
0 : 5
String: 'jack '
5 : 12
List of length 3
12 : 17
String: ' john'
>>> assert len(s) == end

还提供了其他两个方便的方法:has_jsononly_json

>>> has_json('stuff {"key": "value"} things')
True
>>> has_json('stuff only')
False
>>> only_json('stuff {"key": "value"} things')[2]
{u'key': u'value'}
>>> only_json('stuff only')
Traceback (most recent call last):
...
ValueError: No JSON object found in argument.
>>> only_json('{}{}')
Traceback (most recent call last):
...
ValueError: More than one JSON object found in the argument.

所有方法都允许传入自定义的JSONDecoder以增加灵活性。

该库还包括一个命令行工具,用于格式化JSON并根据是否存在JSON过滤输入的一部分。它类似于Python内置的json.tool,一个grep -v for JSON,等等。例如

$ cat cli_example.txt
This line contains no JSON and will be deleted by the --delete other-lines option.
On the other hand {"json":   ["is", "formatted"]  } and text surrounding it is preserved (but can also be removed if desired).
$ jsonfinder -i cli_example.txt --delete other-lines
On the other hand {
    "json": [
        "is",
        "formatted"
    ]
} and text surrounding it is preserved (but can also be removed if desired).
$ jsonfinder -i cli_example.txt --delete other-lines | jsonfinder --delete context --format tiny
{"json":["is","formatted"]}

请参阅命令行的--help 选项以获取更多信息。

安装非常简单

pip install jsonfinder

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分布

jsonfinder-0.4.2.tar.gz (9.5 kB 查看哈希值)

上传时间: 源代码

支持者