简体   繁体   English

使用 JSON.Parse Reviver 转换 object

[英]Using the JSON.Parse Reviver to transform an object

Would it be possible to use the reviver on the JSON.parse function in order to change the structure of the data being parsed?是否可以在 JSON.parse function 上使用 reviver 来更改正在解析的数据的结构?

For example, how can I parse the string below:例如,我如何解析下面的字符串:

fruitString = "{"Apple":2,"Orange":4}";

to the following object?到下面的object?

 fruitPrices: { "Apple":{ "price": 2 }, "Orange":{ "price": 4 } }

What I've tried is:我试过的是:

 let fruitPrices = JSON.parse(fruitString, (key, value) => { return {key: {'price' => value}}; });

But what I'm getting is:但我得到的是:

>      fruitPrices:{
>         key:{
>            price:{
>               Apple:{
>                  key:{
>                     price:2
>                   }
>                }
>               Orange:{
>                  key:{
>                     price:4
>                   }
>                }
>             }
>           }
>        }

Please may you help me understand what I'm doing wrong?请你帮我理解我做错了什么?

Here's how you'd do it with a reviver:以下是你如何使用复苏器来做到这一点:

let fruitPrices = JSON.parse(
    fruitString,
    (key, value) => key === '' ? value : {price: value}
);

That check against empty string is caused by how the reviver walks through the object.对空字符串的检查是由 reviver 如何遍历 object 引起的。 The last iteration happens to take your final object and the key for that final check is always an empty string.最后一次迭代恰好采用了您的最终 object 并且最终检查的密钥始终是一个空字符串。 We don't want to change anything in that final step, so we just return value there.我们不想在最后一步改变任何东西,所以我们只是在那里返回value

No need to wrap with key.无需用密钥包装。 https://jsbin.com/pajosorapa/1/edit?html,js,output https://jsbin.com/pajosorapa/1/edit?html,js,output

 var fruitString = "{\"Apple\":2,\"Orange\":4}"; var fruitPrices = JSON.parse(fruitString, (key, value) => { if (typeof(value) === 'number'){ return { 'price': value }; } return value; }); console.log(JSON.stringify(fruitPrices));

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

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