用python生成带单斜杠的json文件

monwx1rj  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(70)

我有一个json文件如下,其中geometry的值是一个字符串。
我需要在字符串中的每个双引号前面添加一个斜杠
发件人:

{"geometry": 
  "{"type": "LineString", "coordinates": [[25.4907, 35.29833],[25.49187, 35.28897]]}"
}

字符串
收件人:

{"geometry": 
  "{\"type\": \"LineString\", \"coordinates\": [[25.4907, 35.29833], [25.49187, 35.28897]]}"}


我尝试在通过json库导出之前使用replace来实现这一点

obj['geometry'] = str(feat['geometry']).replace("'","\\'")

with open(json_filepath, 'w') as f:
    f.write('\n'.join(map(json.dumps, data)))


但输出是双斜杠:

"geometry": "{\\"type\\": \\"MultiPolygon\\", \\"coordinates\\":
...


如何生成一个只有一个斜杠的文件,谢谢~
--编辑
添加源数据示例:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            121.51749976660096,
            25.04609631049641
          ],
          [
            121.51870845722954,
            25.045781689873138
          ],
          [
            121.51913536000893,
            25.045696164346566
          ]
        ]
      },
      "properties": {
        "model": {
          "RoadClass": "3",
          "RoadClassName": "省道一般道路",
          "RoadID": "300010",
          "RoadName": "臺1線",
          "RoadNameID": "10",
          "InfoDate": "2015-04-01T00:00:00"
        }
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            121.51913536000893,
            25.045696164346566
          ],
          [
            121.51938079578713,
            25.045646605406546
          ],
          [
            121.51946871710766,
            25.0456288491921
          ]
        ]
      },
      "properties": {
        "model": {
          "RoadClass": "3",
          "RoadClassName": "省道一般道路",
          "RoadID": "300010",
          "RoadName": "臺1線",
          "RoadNameID": "10",
          "InfoDate": "2015-04-01T00:00:00"
        }
      }
    }
  ]
}


原始数据是来自一个API的geojson格式。我将要对这个数据做的是将它插入到Geography数据类型的Bigquery中,引用来自here
根据博客,我需要:
1.提取features中的值
1.将geometry中的数据类型更改为字符串
1.在geometry字符串中的每个逗号前添加斜杠

q7solyqu

q7solyqu1#

正如注解中所说,你给予的json不能直接在Python中使用(也不能在json文件中使用)。因此,我决定将其用作Python字典。

import json
from pathlib import Path

dict_to_put_as_json = {
    "geometry": {
        "type": "LineString",
        "coordinates": [[25.4907, 35.29833], [25.49187, 35.28897]],
    }
}

geometry_as_string = json.dumps(dict_to_put_as_json["geometry"])
dict_to_write = {"geometry": geometry_as_string}

with Path("result.json").open(mode="w") as fp:
    json.dump(dict_to_write, fp)

字符串
像这样,它在json文件中给出:

{
  "geometry": "{\"type\": \"LineString\", \"coordinates\": [[25.4907, 35.29833], [25.49187, 35.28897]]}"
}

相关问题