【问题标题】:How can i write the JSON data shown in my Linux terminal to a JSON file using Python如何使用 Python 将我的 Linux 终端中显示的 JSON 数据写入 JSON 文件
【发布时间】:2021-06-08 07:07:35
【问题描述】:

伙计们,这个脚本的作用是:读取一个不是正确 JSON 格式的文件,并将其写入正确的 JSON 格式,但在我的终端上。我希望它直接将读取的数据写入 JSON 文件。我需要它在我的终端窗口中看起来完全一样。 请给我看一个例子,我真的很感激你的帮助。-----> My terminal window with values in correct JSON format

import json
from pprint import pprint




data = []
with open(r"latency.json") as fp:
    while True:
        l= fp.readline()
        if not l:
            break
            
        j = json.loads( l )
        data.append( j )
pprint( data )

【问题讨论】:

  • 您终端中的输出不是有效的 JSON。
  • 这看起来像一个字典列表。实际的 JSON 密钥用 " 引用
  • 如果你的输出没问题,你可以用your_command > output.txt或类似的重定向它。

标签: python json linux terminal


【解决方案1】:
import json
import yaml 

FILE_PATH = ''

with open(f'{FILE_PATH}.json', 'r') as fileRead:
     TEMP = fileRead.readlines()

for line in TEMP:
    DATA = yaml.load(line.strip(), yaml.SafeLoader)
    print(json.dumps(DATA))

【讨论】:

    猜你喜欢
    • 2015-08-27
    • 2014-08-14
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2015-12-09
    • 2012-08-31
    相关资源
    最近更新 更多