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

移除JSON中Location字段的方括号:CSV转JSON适配MongoDB问题

解决方案

问题原因

你代码里groupby后用to_dict('records')会返回包含单个字典的数组——哪怕每个邮编组只有一行数据,to_dict('records')也会以列表形式输出,这就导致Location字段变成了多余的数组格式。

修复方案(两种可选)

方案1:修改原groupby逻辑

先修正字段名错误(CSV里是Postcode而非Postcode 1),再把apply里的逻辑改成返回单个字典:

url = 'National_Statistics_Postcode_Lookup_UK_Coordinates.csv'
fields = ['Postcode', 'Longitude','Latitude']  # 修正字段名匹配CSV结构
df = pd.read_csv(url, skipinitialspace=True, usecols=fields, dtype=str)
df['type'] = 'Point'
df['coordinates'] = df[["Longitude","Latitude"]].values.tolist()
df1 = df[['Postcode','type','coordinates']]

# 调整apply逻辑,取组内第一行直接转成单个字典
df2 = (df1.head(5)
       .groupby(['Postcode'], as_index=False)
       .apply(lambda x: x[['type','coordinates']].iloc[0].to_dict())
       .rename('Location')
       .reset_index()
       .to_json(orient='records'))
print(df2)

方案2:直接构造Location字段(更简洁)

因为每个邮编对应唯一一条记录,完全不需要groupby,直接构造Location字典列即可:

url = 'National_Statistics_Postcode_Lookup_UK_Coordinates.csv'
fields = ['Postcode', 'Longitude','Latitude']
df = pd.read_csv(url, skipinitialspace=True, usecols=fields, dtype=str)

# 直接生成符合要求的Location结构
df['Location'] = df.apply(lambda row: {
    'type': 'Point',
    'coordinates': [row['Longitude'], row['Latitude']]
}, axis=1)

# 选择需要的列输出JSON
df2 = df[['Postcode', 'Location']].head(5).to_json(orient='records')
print(df2)

效果验证

两种方案都会生成你需要的JSON结构:

[
   {
      "Postcode":"BS273EE",
      "Location":{
         "coordinates":["-2.783927","51.275287"],
         "type":"Point"
      }
   }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:23:29