gpt4 book ai didi

json - 如何将 csv 转换为该格式的 json 文件?

转载 作者:行者123 更新时间:2023-12-04 02:10:51 25 4
gpt4 key购买 nike

我有一个像这个示例的 Csv 文件:

0   -8,396  13,414  -35,891 39,22489124
1 -8,789 12,768 -35,891 39,09516883
2 -9,136 12,768 -35,891 39,17463722
3 -9,614 12,768 -35,891 39,2888623
4 -9,614 12,397 -36,282 39,52844709
5 -9,614 12,397 -36,282 39,52844709

我需要将其转换为该格式的 JSON 文件:
{"0": [-12.770680147058824, 1.846047794117647, -54.265625, 55.77863587895704], 
"1": [-18.388229927007298, 6.5360401459854014, -52.65647810218978, 56.156491225545878],
"2": [-20.042738970588236, 12.849264705882353, -46.678308823529413, 52.399231898471129],
"3": [-38.242244525547449, 15.836222627737227, -40.48357664233577, 57.897972254845804],
"4": [-33.016879562043798, 6.3001824817518246, -38.179288321167881, 50.867127813832226]}

你知道我该怎么做吗?

最佳答案

这是使用 jq 的解决方案

reduce (
split("\n")[] # split string into lines
| split("\t") # split into columns
| select(length>0) # eliminate blanks
| map(gsub(",";".")) # change decimal character
) as $r (
{}
; .[$r[0]] = $r[1:] # build requested result
)

filter.jq包含此过滤器和 data包含制表符分隔的数据
0   -8,396  13,414  -35,891 39,22489124
1 -8,789 12,768 -35,891 39,09516883
2 -9,136 12,768 -35,891 39,17463722
3 -9,614 12,768 -35,891 39,2888623
4 -9,614 12,397 -36,282 39,52844709
5 -9,614 12,397 -36,282 39,52844709

样本数据然后
$ jq -M -R -r -s -f filter.jq data | \
sed -e ':a' -e 'N' -e '$!ba' \
-e 's/",\n /",/g' \
-e 's/\[\n /\[/g' \
-e 's/\n \]/\]/g'

产生
{
"0": [ "-8.396", "13.414", "-35.891", "39.22489124"],
"1": [ "-8.789", "12.768", "-35.891", "39.09516883"],
"2": [ "-9.136", "12.768", "-35.891", "39.17463722"],
"3": [ "-9.614", "12.768", "-35.891", "39.2888623"],
"4": [ "-9.614", "12.397", "-36.282", "39.52844709"],
"5": [ "-9.614", "12.397", "-36.282", "39.52844709"]
}

请注意 sed最后只是为这个 Stack Overflow 示例提供更紧凑的 JSON。

关于json - 如何将 csv 转换为该格式的 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38636218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com