简体   繁体   English

如何将JSON字符串转换为JavaScript对象,包括类型检查

[英]How to convert a JSON string into a JavaScript Object including type checking

For a Javascript project I have an json string converted into a Javascript object. 对于Javascript项目,我将json字符串转换为Javascript对象。 But the type of all my values is 'string' becaus of the JSON parsing. 但是我所有值的类型都是JSON解析的“字符串”。
Is there any solution to identify the types and let a script convert them into the correct javascript type? 有什么解决方案可以识别类型并将脚本转换为正确的javascript类型?

for example 例如

//Javascript object for the json decoded string    
var jsonObj = { id: "foo", count: "1" };

All the values are of type 'string' but I want count to be seen as a number. 所有的值都是'string'类型的,但我希望count被视为一个数字。 Is there a parser to set the correct type or does it need to be done manual in JS? 是否有解析器来设置正确的类型,或者它需要在JS中手动完成?

You can use a reviver with JSON.parse . 您可以将reviver与JSON.parse

json2.js describes the reviver thus json2.js描述了json2.js

 JSON.parse(text, reviver) 

The optional reviver parameter is a function that can filter and transform the results. 可选的齐磊参数是可以过滤和转换结果的函数。 It receives each of the keys and values, and its return value is used instead of the original value. 它接收每个键和值,并使用其返回值代替原始值。 If it returns what it received, then the structure is not modified. 如果返回所收到的内容,则不会修改结构。 If it returns undefined then the member is deleted. 如果返回undefined,则删除该成员。

So to convert count to a number you might do 因此要将计数转换为数字,您可能会做

JSON.parse(myJsonString, function (key, value) {
  return key === "count" ? +value : value;
});

so 所以

JSON.stringify(JSON.parse('{ "id": "foo", "count": "3" }', function (key, value) {
  return key === "count" ? +value : value;
}));

produces 产生

{"id":"foo","count":3}

EDIT 编辑

To handle dates as well, you can 要同时处理日期,您可以

JSON.parse(myJsonString, function (key, value) {
  // Don't muck with null, objects or arrays.
  if ("object" === typeof value) { return value; }
  if (key === "count") { return +value; }
  // Unpack keys like "expirationDate" whose value is represented as millis since epoch.
  if (/date$/i.test(key)) { return new Date(+value); }
  // Any other rules can go here.
  return value;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM