跳转到主要内容

流式换行分隔JSON I/O。

项目描述

流式换行分隔JSON I/O。

https://travis-ci.org/geowurster/NewlineJSON.svg?branch=master https://coveralls.io/repos/geowurster/NewlineJSON/badge.svg?branch=master

示例

调用 newlinejson.open() 返回一个类似于Python的 io.TextIOWrapper 的文件-like对象

import newlinejson as nlj

with nlj.open('sample-data/dictionaries.json') as src, \
        with nlj.open('out.json', 'w') as dst:
    for line in src:
        dst.write(line)

with open('out.json') as f:
    print(f.read()))
{'field2': 'l1f2', 'field3': 'l1f3', 'field1': 'l1f1'}
{'field2': 'l2f2', 'field3': 'l2f3', 'field1': 'l2f1'}
{'field2': 'l3f2', 'field3': 'l3f3', 'field1': 'l3f1'}
{'field2': 'l4f2', 'field3': 'l4f3', 'field1': 'l4f1'}
{'field2': 'l5f2', 'field3': 'l5f3', 'field1': 'l5f1'}

命令行界面

而不是提供另一个实用工具,CLI可以通过 python -m newlinejson 访问

$ python -m newlinejson --help
Usage: newlinejson [OPTIONS] COMMAND [ARGS]...

  NewlineJSON commandline interface.

  Common simple ETL commands for homogeneous data.

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  csv2nlj  Convert a CSV to newline JSON dictionaries.
  insp     Open a file and launch a Python interpreter.
  nlj2csv  Convert newline JSON dictionaries to a CSV.

包含的实用工具用于处理同质数据,这意味着每一行都有相同的字段。目标是提供简单的数据转换工具,而不是更全面的套件。

我不能用单个函数完成这个模块的所有功能吗?

基本上 - 这是简单的换行分隔JSON API

import json

def reader(stream):
    for line in stream:
        yield json.loads(line)

with open('sample-data/lists.json') as src, open('outfile.json', 'w') as dst:
    for line in reader(src):
        dst.write(json.dumps(line))

但它不处理失败,每次需要使用它时都需要重新编写,这意味着它需要打包,这意味着它需要unittests,不妨让它更Pythonic,现在我们又回到了这个模块。直接 import newlinejson 并且知道它将工作,比多次解决完全相同的问题要简单得多。

为什么这比MsgPack、Protobuf或其他任何打包二进制格式更好?

这很可能不是。如果您正在寻找一个模块以集成到高容量数据管道或带宽受限的环境中,您肯定需要一个打包的二进制格式。如果您正在处理少量本地数据以生产一次性产品、验证工作流程或希望为从stdin/stdout读取/写入的命令行应用程序提供额外的I/O功能,这个模块非常易于使用。

本模块的目标是以简单直观的方式填补Python生态系统的空白,而不是提供高度优化的I/O。如果Python内置的JSON库不够快,但换行分隔的JSON是您问题的正确答案,可以使用以下方法全局使用许多更快的JSON库之一:在 newlinejson.core.JSON_LIB = module 中,或者在 open()load() 等中使用关键字参数 json_lib=module

安装

通过pip

$ pip install NewlineJSON

>从master

$ git clone https://github.com/geowurster/NewlineJSON.git
$ cd NewlineJSON
$ python setup.py install

开发

安装

$ pip install virtualenv
$ git clone https://github.com/geowurster/NewlineJSON
$ cd NewlineJSON
$ virtualenv venv
$ source venv/bin/activate
$ pip install -e .[test]
$ py.test tests --cov newlinejson --cov-report term-missing
$ pep8 --max-line-length=95 newlinejson

许可证

LICENSE.txt

变更日志

CHANGES.md

项目详情


下载文件

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

源分布

NewlineJSON-1.0.tar.gz (12.3 kB 查看散列)

上传时间

构建分布

NewlineJSON-1.0-py2.py3-none-any.whl (12.8 kB 查看散列)

上传时间 Python 2 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面