Search code examples
javascriptnode.jsjsonjavascript-objects

converting JSON data into javascript Object format


My API is returning data into the below format.

{
    "name": "Mahima",
    "surname": "Saxena",
}

I need to convert the same into below format.

{
    name: "Mahima",
    surname: "Saxena",
}

I need to remove double quote(" ") from key . how can I do this?

I tried below code.

var abc = {
  "name": "Mahima",
  "surname": "Saxena",
};
console.log(abc);
console.log(JSON.parse(abc));

I am getting error in code.

enter image description here

what mistake I am doing?


Solution

  • You are misunderstanding the concept of "json string". It is easy as it looks like how javascript typically shows the contents of an object. I have stumbled on this myself.

    See

    JSON.parse(abc)
    

    The method 'parse' takes an argument that must be a string. It then returns an object.

    You already have an object in abc with

    var abc = {
      "name": "Mahima",
      "surname": "Saxena",
    };
    

    So there is no need to convert anything.

    The formats

    {
        "name": "Mahima",
        "surname": "Saxena",
    }
    

    and

    {
        name: "Mahima",
        surname: "Saxena",
    }
    

    are the same. They are 1 object with the properties name and surname.