How to rename JSON key

后端 未结 11 700
名媛妹妹
名媛妹妹 2020-11-27 12:46

I have a JSON object with the following content:

[
  {
    \"_id\":\"5078c3a803ff4197dc81fbfb\",
    \"email\":\"user1@gmail.com\",
    \"image\":\"some_imag         


        
11条回答
  •  再見小時候
    2020-11-27 13:25

    JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.

    In reviver function:

    • if we return undefined, the original property will be deleted.
    • this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.
    const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}]';
    
    const obj = JSON.parse(json, function(k, v) {
        if (k === "_id") {
            this.id = v;
            return; # if return  undefined, orignal property will be removed
        }
        return v;
    });
    
    const res = JSON.stringify(obj);
    console.log(res)
    

    output:

    [{"email":"user1@gmail.com","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"user2@gmail.com","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]
    

提交回复
热议问题