检查json值是否与前导零匹配的数字并将其转换为字符串 [英] Check if a json value match a number with leading zero and convert it to a string
问题描述
我有一个从PhpMyAdmin导出的Json文件.我需要将其转换为javascript对象,甚至更好地转换为javascript数组.我正在使用 Nodejs模块 fs.readFile()
读取文件,并使用Json.parse()
函数将字符串转换为对象,但是当找到前导零的数字时,该函数将挂起.我需要将数字转换为字符串.任何建议将不胜感激.
I have a Json file exported from PhpMyAdmin. I need to convert it to a javascript object or even better to a javascript array. I'm using Nodejs module fs.readFile()
to read the file and Json.parse()
function to convert the string to an object, but this function hang when it finds a number with leading zero. I need to convert the number to a string. Any suggestions would be really appreciated.
这是直接从PhpMyadmin导出的json文件的内容:
here is the content of a json file exported directly from PhpMyadmin:
[{"id": 1,"country": 0,"code":056897,"customer":"Joe Harris"},{"id": 2,"country": 2,"code":054597,"customer":"Frank Foe"}]
我想将其转换为带有节点的Javascript对象:
I want to convert it in a Javascript object with node:
var fs = require('fs');
var docs = fs.readFile('dbfiles/countries.json','utf8', function (err, data) {
if (err) throw err;
//code needed here to convert numbers with leading zero in string
var docsJsonData = JSON.parse(data);
});
推荐答案
理想情况下,如果可以使phpMyAdmin发出有效的JSON,那将是最佳选择.
Ideally, if you could cause phpMyAdmin to emit valid JSON, that would be the best choice.
但是,您可以使用正则表达式进行一些合理的自定义修正.例如,您给出的示例:
However, you could do some reasonable custom fixups using regular expressions. For example, the example you gave:
// data is from the file
// match on "code":0####
var fixCode = /"code":(0[0-9]+),/g;
var results = JSON.parse(
data.replace(fixCode, function(match, code) {
// rebuild the "code" property with quotes
// (or convert to a VALID number):
return '"code": "' + code + '", ';
}));
结果:
[ { id: 1,
country: 0,
code: '056897',
customer: 'Joe Harris' },
{ id: 2,
country: 2,
code: '054597',
customer: 'Frank Foe' } ]
这篇关于检查json值是否与前导零匹配的数字并将其转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!