gpt4 book ai didi

javascript - Papa 解析返回 Data 数组,其中所有内容都转换为字符串

转载 作者:行者123 更新时间:2023-11-28 12:15:10 25 4
gpt4 key购买 nike

我正在使用 React 将 .CSV 解析为 Papa.parse,我得到的输出如下:

[
{Year: "1929", BMW: "1896", Toyots: "9547", Mercedes: "4881"},
{Year: "1930", BMW: "6548", Toyots: "4741", Mercedes: "8096"},
{Year: "1931", BMW: "5013", Toyots: "6269", Mercedes: "3908"},
{Year: "1932", BMW: "2468", Toyots: "9858", Mercedes: "1623"},
{Year: "1933", BMW: "3364", Toyots: "5595", Mercedes: "8638"},
{Year: "1934", BMW: "2032", Toyots: "2570", Mercedes: "8041"},
{Year: "1935", BMW: "3579", Toyots: "6886", Mercedes: "6938"},
{Year: "1936", BMW: "2865", Toyots: "3336", Mercedes: "1996"}
]

问题是 Papa.parse 将所有内容转换为双引号下的 string!

我们如何将它们转换回数字? (如果它们的原始形式是数字!问题是某些字段可能没有数字类型,例如位置或地址或名称:它们是字符串拼写错误)

或者是否有任何配置可以防止 Papa.parse 这样做?

最佳答案

启用dynamicTyping选项以保留数字:

const csv = "Year,BMW,Toyota,Mercedes,Location\n1929,1896,9547,4881,Germany"
const csvData = Papa.parse(csv, {header:true, dynamicTyping: true}).data

console.log(typeof csvData[0].Year);
console.log(typeof csvData[0].Location);
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.5.0/papaparse.min.js">
</script>

关于javascript - Papa 解析返回 Data 数组,其中所有内容都转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203634/

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