如何将重复键值对格式的文本文件转换为JSON格式?
将特定格式文本转换为JSON的方法
问题描述
我有一个格式如下的文本文件:
Cus Id: 1234 Cus Name: 10:/John Parks Cus Type: temporary Cus client: tesla;toyota Dept Id: 111 Cus Id: 1235 Cus Name: 10:/William Parks Cus Type: temporary Cus client: Dept Id: 222
需要将其转换为如下JSON格式:
[ { "Cus Id": 1234, "Cus Name": "10:/John Parks", "Cus Type": "temporary", "Cus client": "tesla;toyota", "Dept Id": 111 }, { "Cus Id": 1235, "Cus Name": "10:/William Parks", "Cus Type": "temporary", "Cus client": "null", "Dept Id": 222 } ]
方法一:使用Bash + jq
通过bash文本处理工具结合jq完成转换,执行以下命令:
awk -v RS='' -v FS='\n' '{ print "{" for(i=1; i<=NF; i++) { split($i, arr, /: /) key = arr[1] value = arr[2] if (value == "") value = "\"null\"" else if (key ~ /Id$/) printf " \"%s\": %s", key, value else printf " \"%s\": \"%s\"", key, value if (i < NF) print "," } print "}" }' input.txt | jq -s '.'
说明
awk -v RS='':以空行作为记录分隔符,把每个客户的信息当成一条独立记录split($i, arr, /: /):按:加空格分割每行的键值对- 对空值的
Cus client设置为"null",对以Id结尾的字段输出数字类型,其他字段输出字符串类型 jq -s '.':将所有生成的对象包裹成一个JSON数组
方法二:使用Python脚本
编写如下Python脚本(保存为convert_to_json.py):
import json def convert_file(input_path): customers = [] current_customer = {} with open(input_path, 'r') as f: for line in f: line = line.strip() if not line: # 遇到空行,保存当前客户信息并重置 if current_customer: customers.append(current_customer) current_customer = {} continue # 分割键值对 key, _, value = line.partition(': ') # 处理空值 if not value: value = "null" # 处理Id字段的数字类型 if key.endswith('Id'): value = int(value) current_customer[key] = value # 处理最后一个客户的信息 if current_customer: customers.append(current_customer) # 输出格式化后的JSON print(json.dumps(customers, indent=2)) if __name__ == "__main__": convert_file("input.txt")
使用方式
在终端运行:
python convert_to_json.py
内容的提问来源于stack exchange,提问作者Warren Jacob
相关产品推荐
相关产品推荐

