有没有办法从 .json 文件中的数值中删除双引号?

问题描述 投票:0回答:1

我一直在尝试使用 folium 库在某个时间范围内的地图上绘制点,因此我从 .txt 创建了一个 .json 文件,其中填充了我的时间和坐标值。但是,该 .json 文件中的所有数值现在都用双引号引起来。看起来像这样:

[
    {
        "lat": "37.79185",
        "lon": "-122.4159",
        "aoe": "1695149258521.0"
    },
    {
        "lat": "37.79185",
        "lon": "-122.4159",
        "aoe": "1695149260911.0"
    }
]

我希望它们看起来像这样:

[
    {
        "lat": 37.79185,
        "lon": -122.4159,
        "aoe": 1695149258521.0
    },
    {
        "lat": 37.79185,
        "lon": -122.4159,
        "aoe": 1695149260911.0
    }
]

我通过稍微更改我在网上找到的代码,从 .txt 创建了 .json:

filename = 'Lat_Lon_Time.txt'
dict1 = []
fields =['lat','lon','aoe']
 
with open(filename) as fh:

    for line in fh:

        description = list( line.strip().split(None, 4))

        i = 0
        dict2 = {}
        while i<len(fields):

                dict2[fields[i]]= description[i]
                i = i + 1
               
        dict1.append(dict2)
    
out_file = open("test2.json", "w")
json.dump(dict1, out_file, indent = 4)
out_file.close()

我尝试更改这段代码以直接删除引号,但我不知道该怎么做。 我也尝试过使用正则表达式在事后取出引号,但我也不太确定如何做到这一点。 当我寻找解决方案时,我发现这两个问题与我的类似 - 但我对 Python 很陌生,我不明白如何在我的特定情况下实现这些解决方案。

正则表达式:从 Json 值中删除双引号 如何删除 JSON stringify 对象中数字周围的引号?

是否可以立即更改初始代码来创建不带双引号的数值的 .json,或者在文件创建后使用正则表达式将它们取出?

json string strip folium
1个回答
0
投票

问题是,当您开始读取它们时,您将它们作为字符串而不是浮点数读取。这段代码应该处理这个问题。

import json

filename = 'Lat_Lon_Time.txt'
dict1 = []
fields = ['lat', 'lon', 'aoe']

with open(filename) as fh:
    for line in fh:
        description = list(line.strip().split())

        dict2 = {}
        for i, field in enumerate(fields):
            if field in ['lat', 'lon']:
                dict2[field] = float(description[i])
            else:  # If 'aoe' is the only other field...?
                dict2[field] = float(description[i])

        dict1.append(dict2)

with open("test2.json", "w") as out_file:
    json.dump(dict1, out_file, indent=4)
© www.soinside.com 2019 - 2024. All rights reserved.