You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求支持多数据类型的Key=Value文本转JSON工具库

推荐可将Key=Value格式文本转换为JSON的工具库

你的需求核心是正确识别并转换多种数据类型(字符串、数字、布尔值、JSON对象、数组),普通的键值对解析库(如仅处理.env文件的工具)通常只支持字符串,无法满足要求,以下是适配不同语言的解决方案:

通用方案:TOML解析器

你的输入格式完全符合TOML的基础语法,TOML原生支持所有你提到的数据类型,主流语言都有成熟的TOML解析库,解析后可直接序列化为JSON:

Python示例(toml库)

import toml
import json

# 读取你的Key=Value文本内容
input_content = """
name = "test"
version = 3
enabled = true
fruit = {"type":"orange","color":"orange"}
consumers = ["kids", "adults"]
years = [2014, 2015]
fruits = [{"type":"orange","color":"orange"},{"type":"apples","method":"red"}]
"""

# 解析并转换为JSON
parsed_data = toml.loads(input_content)
json_output = json.dumps(parsed_data)
print(json_output)

Node.js示例(@iarna/toml库)

const toml = require('@iarna/toml');
const inputContent = `
name = "test"
version = 3
enabled = true
fruit = {"type":"orange","color":"orange"}
consumers = ["kids", "adults"]
years = [2014, 2015]
fruits = [{"type":"orange","color":"orange"},{"type":"apples","method":"red"}]
`;

const parsedData = toml.parse(inputContent);
console.log(JSON.stringify(parsedData));

其他语言可用的TOML库:

  • Java:toml4j
  • Go:github.com/BurntSushi/toml
  • C#:Tomlyn

替代方案:HOCON解析器

HOCON是更灵活的配置格式,同样支持你的键值对结构和复杂数据类型,适合需要额外配置特性的场景:

Python示例(pyhocon库)

from pyhocon import ConfigFactory
import json

input_content = """
name = "test"
version = 3
enabled = true
fruit = {"type":"orange","color":"orange"}
consumers = ["kids", "adults"]
years = [2014, 2015]
fruits = [{"type":"orange","color":"orange"},{"type":"apples","method":"red"}]
"""

config = ConfigFactory.parse_string(input_content)
json_output = json.dumps(config)
print(json_output)

这些解析库都会自动处理所有数据类型的转换,输出完全符合要求的合法JSON。

内容的提问来源于stack exchange,提问作者MFabricanti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:45:36