如何将JSON字符串更改为Long / Double / Number

时间:2017-05-10 17:00:45

标签: json node.js string double converter

我有一个像这样的JSON:

{ “id_document”:“12345679”, “名字”:“John SMmith”, “价值”:“127,30” }

我想将“value”字段更改为Double / Number,如下所示:

{ “id_document”:“12345679”, “名字”:“John SMmith”, “价值”:127.30 }

问题是我有很多JSON数据,例如70k行。所以我需要一种自动化方法。 有没有人有任何想法?

可以用任何语言进行解决。我在尝试NodeJS。

感谢帮助人员。

编辑:

我的JSON文件类似于:

{“DESPESA”:[{“sgPartido”:“DEM”,“numMes”:1,“txtCNPJCPF”:“03625917000170”,“vlrGlosa”:“0”,“txNomeParlamentar”:“ABEL MESQUITA JR。” ,“sgUF”:“RR”,“nuCarteiraParlamentar”:1,“vlrDocumento”:“4007,06”,“nuDeputadoId”:3074,“numSubCota”:3,“txtDescricaoEspecificacao”:“VeículosAutomotores”,“txtPassageiro”: null,“datEmissao”:null,“codLegislatura”:55,“vlrRestituicao”:“0”,“numParcela”:0,“txtDescricao”:“COMBUSTÍVEISELUBRIFICANTES。”,“txtNumero”:“4339”,“numEspecificacaoSubCota” :1,“txtFornecedor”:“BB PETROLEO LTDA”,“numLote”:1354058,“indTipoDocumento”:0,“idecadastro”:178957,“numAno”:2017,“txtTrecho”:null,“numRessarcimento”:5711,“ vlrLiquido“:”4007,06“,”ideDocumento“:6196889,”nuLegislatura“:2015},... 70k行与此类和结束的对象}

编辑:我做过的人,结果就是:

fs = require('fs');
var in_file = 'in.json';
var out_file = 'out.json' 
fs.readFile(in_file, 'utf8', function(err, data) {
data = JSON.parse(data);

for(let i in data.DESPESA) {
    let despesa = data.DESPESA[i];
    let valor = despesa.vlrDocumento.replace(',', '.');
    data.DESPESA[i].vlrDocumento = parseFloat(valor);
}

fs.writeFile(out_file, JSON.stringify(data), function(err) {
    if (err) throw err;
        console.log('The file has been saved!');
});
});
谢谢你的帮助,答案有所不同。

1 个答案:

答案 0 :(得分:0)

假设您的数据是一个对象数组,您应该看看Array.proptoy.map然后您可以编写一个函数来解析您的 对象,并将数据从字符串转换为数字,例如:

const myData = JSON.parse(<data from file>);
const parsedData = mydata.map(function(val) {
   val.value = parseFloat("554,20".replace(",", "."));
   return val;
});

//go back to JSON:
JSON.stringify(parsedData);

(parseFloat计算来自this answer