Sunil Prabakar
Sunil Prabakar

Reputation: 442

JSON.Stringify replacer function not able to get key value

I am using JSON.stringify and its replacer parameter. But in replacer parameter i am not able to get key and value, instead of i got key value as empty string "" and value as complete JSON object. What mistake i have done in my code? please clear it.

var replacer=function(key,value){
        debugger; 
    }
    $(function () {
       JSON.stringify({"name":'xxxxx'},replacer)
    });

I need to get key as "name" and value as "xxxxx"

Upvotes: 1

Views: 1869

Answers (2)

t.niese
t.niese

Reputation: 40872

MDN - JSON.stringify(): The replacer parameter:

[...]Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.[...]

In your first iteration you get the whole object {"name":'xxxxx'} as value, but because you return undefined from your replace function the whole object will be replaced by undefined, and because of that the next iteration with the value/key pairs does not take place.

If you return the value you will see that the next iteration takes place.

var replacer = function(key, value) {
  console.dir(arguments);
  return value;
}

JSON.stringify({
  "name1": 'xxxxx'
}, replacer);

Upvotes: 7

Elad
Elad

Reputation: 971

var replacer=function(key,value){
    var json_obj = JSON.parse(value);
    var name = json_obj.name;

}
$(function () {
   JSON.stringify({"name":'xxxxx'},replacer)
});

Upvotes: -1

Related Questions