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

批量JSON文件中为坐标数组添加键名的实现代码参考问询

注意事项

首先你给出的目标输出格式不符合标准JSON规范:数组[]不能直接存储键值对结构,合理的标准格式应该是将coordinates改为对象类型{},如下:

{"name":"abc", "location": {"coordinates": {"latitude":-94.350096,"longitude":39.049484}}}

如果确实需要保留你示例中的非标准格式,可参考下文的字符串替换方案。


Python 实现代码(标准JSON格式输出)

以下代码适配你提供的JSON Lines格式输入(每行一个JSON对象),处理10000条数据耗时不足1秒,性能无压力:

import json

# 替换为你的输入、输出文件路径
input_file = "your_input_file.txt"
output_file = "processed_output.jsonl"

with open(input_file, "r", encoding="utf-8") as f_in, open(output_file, "w", encoding="utf-8") as f_out:
    for line in f_in:
        line = line.strip()
        if not line:
            continue
        # 解析单条JSON数据
        item = json.loads(line)
        # 提取坐标值,注意常规GEO坐标数组顺序是[经度, 纬度],如果你的数据顺序相反可自行调整
        longitude, latitude = item["location"]["coordinates"]
        # 替换coordinates为带键名的对象
        item["location"]["coordinates"] = {
            "latitude": latitude,
            "longitude": longitude
        }
        # 写入处理后的数据
        f_out.write(json.dumps(item, ensure_ascii=False) + "\n")

非标准格式输出方案(不推荐,仅适配你给出的示例格式)

如果你必须输出示例中的数组包裹键值对的非标准格式,可以用正则替换直接处理字符串:

import re

input_file = "your_input_file.txt"
output_file = "non_standard_output.txt"

with open(input_file, "r", encoding="utf-8") as f_in, open(output_file, "w", encoding="utf-8") as f_out:
    for line in f_in:
        processed_line = re.sub(
            r'"coordinates":\s*\[\s*(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)\s*\]',
            r'"coordinates": ["latitude":\1,"longitude":\2]',
            line
        )
        f_out.write(processed_line)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:06:04