简体   繁体   English

将基于文本的键/值对转换为 JSON 格式

[英]Convert text based key/value pair to JSON format

I have a text file with a lot of key/value pairs in the given format:我有一个text文件,其中包含给定格式的许多键/值对:

secret_key="XXXXX"
database_password="1234"
timout=30
.
.
.
and list continues...

I want these key/value pairs to be stored in a JSON format so that I can make use of this data in the JSON format.我希望这些键/值对以JSON格式存储,以便我可以使用JSON格式的数据。 Is there any way of doing this.有没有办法做到这一点。 I mean any website or any method to do it automatically?我的意思是任何网站或任何方法可以自动完成?

As I guess that is an .env file.我猜这是一个.env文件。 So, I would suggest you try to implement something like this in Python:所以,我建议你尝试在 Python 中实现这样的东西:

import json
import sys

try:
    dotenv = sys.argv[1]
except IndexError as e:
    dotenv = '.env'

with open(dotenv, 'r') as f:
    content = f.readlines()

# removes whitespace chars like '\n' at the end of each line
content = [x.strip().split('=') for x in content if '=' in x]
print(json.dumps(dict(content)))

Reference: https://gist.github.com/GabLeRoux/d6b2c2f7a69ebcd8430ea59c9bcc62c0参考: https://gist.github.com/GabLeRoux/d6b2c2f7a69ebcd8430ea59c9bcc62c0

*Please let me know if you want to implement it in a different language, such as JavaScript. *如果您想用其他语言实现它,请告诉我,例如 JavaScript。

The Python 3.8 script below would do the job ◡̈下面的 Python 3.8 脚本可以完成这项工作◡̈

import json

with open('text', 'r') as fp:
    dic = {}
    while line:=fp.readline().strip():
        key, value = line.split('=')
        dic[key] = eval(value)
    print(json.dumps(dic))

Note: eval is used to prevent double quotes being escaped.注意: eval用于防止双引号被转义。

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

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