How to rename JSON key

后端 未结 11 573
名媛妹妹
名媛妹妹 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"}]
    
    0 讨论(0)
  • 2020-11-27 13:25

    If anyone needs to do this dynamically:

    const keys = Object.keys(jsonObject);
    
    keys.forEach((key) => {
    
          // CREATE A NEW KEY HERE
          var newKey = key.replace(' ', '_');
    
          jsonObject[newKey] = jsonObject[key];
          delete jsonObject[key];
       });
    

    jsonObject will now have the new keys.

    IMPORTANT:

    If your key is not changed by the replace function, it will just take it out of the array. You may want to put some if statements in there.

    0 讨论(0)
  • 2020-11-27 13:26

    If your object looks like this:

    obj = {
        "_id":"5078c3a803ff4197dc81fbfb",
        "email":"user1@gmail.com",
        "image":"some_image_url",
        "name":"Name 1"
       }
    

    Probably the simplest method in JavaScript is:

    obj.id = obj._id
    del object['_id']
    

    As a result, you will get:

    obj = {
        "id":"5078c3a803ff4197dc81fbfb",
        "email":"user1@gmail.com",
        "image":"some_image_url",
        "name":"Name 1"
       }
    
    0 讨论(0)
  • 2020-11-27 13:26

    If you want to do it dynamically, for example, you have an array which you want to apply as a key to JSON object:

    your Array will be like :

    var keys = ["id", "name","Address","Phone"] // The array size should be same as JSON Object keys size
    

    Now you have a JSON Array like:

    var jArray = [
      {
        "_id": 1,
        "_name": "Asna",
        "Address": "NY",
        "Phone": 123
      },
      {
        "_id": 2,
        "_name": "Euphoria",
        "Address": "Monaco",
        "Phone": 124
      },
      {
        "_id": 3,
        "_name": "Ahmed",
        "Address": "Mumbai",
        "Phone": 125
      }
    ]
    
    $.each(jArray ,function(pos,obj){
        var counter = 0;
        $.each(obj,function(key,value){
            jArray [pos][keys[counter]] = value;
            delete jArray [pos][key];
            counter++;
        })  
    })
    

    Your resultant JSON Array will be like :

    [
      {
        "id": 1,
        "name": "Asna",
        "Address": "NY",
        "Phone": 123
      },
      {
        "id": 2,
        "name": "Euphoria",
        "Address": "Monaco",
        "Phone": 124
      },
      {
        "id": 3,
        "name": "Ahmed",
        "Address": "Mumbai",
        "Phone": 125
      }
    ]
    
    0 讨论(0)
  • 2020-11-27 13:28

    By using map function you can do that. Please refer below code.

    var userDetails = [{
      "_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"
    }];
    
    var formattedUserDetails = userDetails.map(({ _id:id, email, image, name }) => ({
      id,
      email,
      image,
      name
    }));
    console.log(formattedUserDetails);
    
    0 讨论(0)
  • 2020-11-27 13:31

    As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,

    var 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"}];
        
    json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));
    
    document.write(JSON.stringify(json));

    This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string.

    0 讨论(0)
提交回复
热议问题