我希望将标准JSON对象操作为对象,其中每行必须包含一个独立的、自包含的有效JSON对象.见JSON Lines

JSON_file =

[{u'index': 1,
  u'no': 'A',
  u'met': u'1043205'},
 {u'index': 2,
  u'no': 'B',
  u'met': u'000031043206'},
 {u'index': 3,
  u'no': 'C',
  u'met': u'0031043207'}]

To JSONL:

{u'index': 1, u'no': 'A', u'met': u'1043205'}
{u'index': 2, u'no': 'B', u'met': u'031043206'}
{u'index': 3, u'no': 'C', u'met': u'0031043207'}

My current solution is to read the JSON file as a text file and remove the [ from the beginning and the ] from the end. Thus, creating a valid JSON object on each line, rather than a nested object containing lines.

I wonder if there is a more elegant solution? I suspect something could go wrong using string manipulation on the file.

The motivation is to read json files into RDD on Spark. See related question - Reading JSON with Apache Spark - `corrupt_record`

推荐答案

Your input appears to be a sequence of Python objects; it certainly is not valid a JSON document.

If you have a list of Python dictionaries, then all you have to do is dump each entry into a file separately, followed by a newline:

import json

with open('output.jsonl', 'w') as outfile:
    for entry in JSON_file:
        json.dump(entry, outfile)
        outfile.write('\n')

The default configuration for the json module is to output JSON without newlines embedded.

假设您的ABC名称实际上是字符串,那么将生成:

{"index": 1, "met": "1043205", "no": "A"}
{"index": 2, "met": "000031043206", "no": "B"}
{"index": 3, "met": "0031043207", "no": "C"}

如果您从包含条目列表的JSON文档开始,只需先用json.load()/json.loads()解析该文档即可.

Json相关问答推荐

VBA json按特定属性名称提取所有数据

如何在Android中解析带有动态键和可变对象名称的改装JSON响应?

在 json 对象中存储多个键:值对

将 json 转换为 jsonb 安全吗?

从 oracle 数据库中的 json blob 打印值

如何编写 jolt 规范以将不同的对象转换为数组

如果有 1 个元素,如何防止 ConvertFrom-Json 折叠嵌套数组

hook到 Decodable.init() 以获得未指定的键?

如何从 rails 中的 respond_to 方法生成 json?

JSON.NET 中特定对象的自定义转换

将 ES6 类对象序列化为 JSON

Newtonsoft Json 将值 {null} 转换为类型System.Int32时出错

如何为名称/值 struct 创建 JSON 模式?

Spring MVC:不反序列化 JSON 请求正文

Swift :将 struct 转换为 JSON?

Spring restTemplate 获取原始 json 字符串

NSManagedObject 属性值的 NSNull 处理

如何将单引号转义成双引号转成单引号

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

将对象序列化为 JSON 时循环引用检测到异常