javascript - json数据值类型

标签 javascript php json

我想将 json 数组值从字符串更改为来自 php 脚本的浮点值。都是字符串类型。我想要它作为浮点类型。

[{"year":"2008","value":"4169.20"},
{"year":"2009","value":"4067.50"},
{"year":"2010","value":"4848.40"},
{"year":"2011","value":"5654.80"},
{"year":"2012","value":"6071.50"}]

但我希望它看起来像。可能吗?

[{"year":"2008","value":4169.20},
{"year":"2009","value":4067.50},
{"year":"2010","value":4848.40},
{"year":"2011","value":5654.80},
{"year":"2012","value":6071.50}]

最佳答案

最简单的方法是在将数据编码为 JSON 之前将 value 转换为 float。

但是如果你只想在 JS 中工作:

var data = [ /* your data */ ];

data.forEach(function(item){
  item.value = +item.value;
});

输出:

[
  {"year":"2008","value":4169.2},
  {"year":"2009","value":4067.5},
  {"year":"2010","value":4848.4},
  {"year":"2011","value":5654.8},
  {"year":"2012","value":6071.5}
]

关于javascript - json数据值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27293482/

相关文章:

json - 在 Kubernetes 中为 kubectl 创建用户

jquery - 为什么我的 YQL 查询在 jQuery 中返回空结果,而相同的 YQL 查询在 YQL 控制台返回正值?

javascript - jQuery/Javascript Uncaught SyntaxError : Unexpected End of Input

javascript - 在 WordPress 主页上添加地理位置

php - 带有 number_format 的图表

php - 使用php传递变量的问题

json - 嵌套的 Go Structs,用于带有可选结构的 JSON 编码(marshal)处理

javascript - Angular/Javascript Luxon - 将时间戳更改时间转换为当前用户时区

Javascript 新手陷入 XMLHttpRequest 返回数据困境

javascript - Angular "controller as syntax" "this"数据