Sunil Prabakar Sunil Prabakar - 6 months ago 74
Javascript Question

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){
$(function () {

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


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) {
  return value;

  "name1": 'xxxxx'
}, replacer);