logo
down
shadow

Unexpected behavior in JSON.parse Reviver function, deleting the object and not the key properties


Unexpected behavior in JSON.parse Reviver function, deleting the object and not the key properties

By : Steve Lambert
Date : November 20 2020, 11:01 PM
hope this fix your issue Your second example left return value; off.
But even tough you did that, it should only have removed the properties that returned undefined as value, and I think you found a bug (may be?).
code :
if (name == "") {
  return value;
}
obj = {
   one: 1,
   innerObj: {
     two: 2,
     four: 4
   },
   two: 2,
   three: 3,
   four: 4
};
b = {};
json = JSON.stringify(obj);


/**
* This does not work as expected, instead of deleting the property on the object, the entire object returns undefined.
*/
b = JSON.parse(json, function (name, value) {
  if (value % 2 === 0) {
    return -value;
  }
  if (name == "") {
    return value;
  }
});
console.log(b);
// { two: -2, four: -4 }


Share : facebook icon twitter icon
JSON.parse reviver function has n+1 keys?

JSON.parse reviver function has n+1 keys?


By : Mohammad Mohsin
Date : March 29 2020, 07:55 AM
I wish this helpful for you I wanted to test the code overload which can provide a reviver function when parsing a JSON string. , The answer is in the link you provided...
JSON.parse using reviver function

JSON.parse using reviver function


By : valerieann Bawn
Date : March 29 2020, 07:55 AM
Hope this helps After checking for the special case(s), you simply need to pass back unmodified values by default:
code :
var myObj = new Object();
myObj.firstname = "mike";
myObj.lastname = "smith";

var jsonString = JSON.stringify(myObj);
var jsonObj = JSON.parse(jsonString, dataReviver);

function dataReviver(key, value)
{ 
    if(key == 'lastname')
    {
        var newLastname = "test";
        return newLastname;
    }

  return value;  // < here is where un-modified key/value pass though

}

JSON.stringify(jsonObj )// "{"firstname":"mike","lastname":"test"}" 
JSON.parse with reviver parameter to whitelist object fields

JSON.parse with reviver parameter to whitelist object fields


By : Sudi
Date : March 29 2020, 07:55 AM
I wish this helpful for you The reviver callback is called for each property of the JSON object, including nested properties, and finally for the object itself. So the last call of the reviver callback will get key = '' and value = [the JSON object] as arguments. '' is not equal to 'a', so your reviver callback returns undefined when it is called for the last time for the whole object. This is why you see undefined for your "whitelisting" approach.
Another problem will arise when you use your approach on nested objects:
code :
var test = "{\"a\": { \"a\": \"A\", \"d\": \"D\" }, \"b\": \"B\", \"c\": \"C\"}";

console.log(JSON.parse(test, function(key, val){ if (key === "a" || key === "") return val; }));
//  { a: { a: 'A' } }  <-- property d is missing
var whitelist = ['a'];
for (var prop in jsonObject) {
    if (!jsonObject.hasOwnProperty(prop)) continue;
    if (whitelist.indexOf(prop) === -1) delete jsonObject[prop];
}
How do I use `JSON.parse`'s reviver function to add data to each object in an array?

How do I use `JSON.parse`'s reviver function to add data to each object in an array?


By : Aurélie Leportier
Date : March 29 2020, 07:55 AM
I wish this helpful for you You don't need to create a new object. The map function, if used correctly, will return a new array(with new objects). And you can use the index provided by map to get your id.
DEMO
code :
var musicList = {
  "files": [
        {
          "title": "Ironic"
        },
        {
          "title": "It's Beginning To Look A Lot Like Christmas"
        },
        {
          "title": "Sweet Dreams"
        }
      ] 
};

var stringifiedMusic = JSON.stringify(musicList);

var parsedMusic = JSON.parse(stringifiedMusic, function(key, value) {

  if (key === 'files') {
    return value.map(function (item, index) {
      item.id = index;
      return item;
    });
  }
  return value;
});

console.log("parsedMusic", parsedMusic)
What is the problem with this JSON.parse reviver function?

What is the problem with this JSON.parse reviver function?


By : John Cosker
Date : March 29 2020, 07:55 AM
it fixes the issue The last call to reviver will happen with an empty string as the key "", which allows you to apply a transformation to the final object (in your case, you're transforming it to undefined). If you add a test for the empty string then it works properly:
code :
const whitelist = ['prop1', 'prop2', 'result'];
const reviver = (key, value) => {
  if (whitelist.includes(key) || key === '') {
    return value;
  } else {
    return undefined; // explicitly delete the entry
  }
};

const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }';

console.log( JSON.parse( theMightyJsonString, reviver ) );
Related Posts Related Posts :
  • Javascript normal Array value and Array value created by match function comparison
  • pass a value from javascript to html and codeigniter
  • how to perform div hover shows another div but both div's are different form?
  • Draw a buffer with subbuffers webgl
  • Call a function on click event in Angular 2
  • Object.assign getters and setters in constructor
  • Have to set Number of Threads, Ramp up Period and Loop count from an external properties file
  • Post data from javascript to php file using ajax doesn't work
  • How to access method in prototypal inheritance pattern?
  • Q: How do I make each div fade away individually?
  • JavaScript/jQuery: how to get HTML and display HTML, including tags
  • Controller not loading if javaScript containing controller code is added dynamically to HTML dom
  • TypeError while retriving prototype properties
  • Google Maps API: adding zip code boundaries
  • Validating date with current date using jquery
  • ComponentWillMount keeps being called repeately
  • Laravel URL Generator With Angular JS Varible
  • Post data to another php page using ajax
  • Progressbar behavior depending on checkboxes bootstrap + jquery
  • node.js/socket.io/express execution order
  • nested EJS tag. Not working
  • Service call in controller in AngularJs using ES6
  • Div that acts as file upload?
  • Load D3 Url With API key
  • Read data in JSON format asp.net View in MVC
  • How to make separate force layout render loop?
  • Download a JSON behind a login page with nightmare
  • Regex to scan for a specific number of a repeating character
  • Array push still using previous reference?
  • Javascript context.closePath() method does not appear
  • Javascript variable undefined even after defining in Express Js, mongo db
  • How to add hover effect to <table> using CKEditor?
  • Autocomplete List Fixed Position Browser Resize
  • RegEx trying to match anything but a certain pattern with chars from the pattern being allowed
  • Validating value in HTML number input with Konva
  • Is any class object serializable in javascript?
  • 'content-type': 'text/html' not accepted until server is killed
  • Vue js Ready function is not triggered
  • setInterval wont work if timing is too short
  • Do reserved words need to be quoted when set as property names of JavaScript objects?
  • How to specify (optional) default props with TypeScript for stateless, functional React components?
  • reactjs render array of objects into a list gives an error
  • Todo list takes 30 seconds to appear
  • Reformat JSON objects inside an array to show them in HTML
  • can not route with angularjs
  • Running a script in a site that copies all keys pressed while the page is open
  • Using jQuery to select div with class signed by ruby iteration
  • Using classList when element is set to display none
  • Ionic 2 Express call not responding to user update function
  • Include background-image url css in jquery string
  • How to optimize jQuery.getJSON() for geolocalisation
  • Vue 2.0 setting up routes - Do not use 'new' for side effects
  • In JavaScript, how to update attributes with jQuery
  • JSON Data not appearing on marker in Google map
  • Why appendChild is not working with node type?
  • Javascript function results
  • Add multiple callback responses to array
  • Parsley's EXCLUDED not recognizing :last
  • Make javaScript (not JQuery!) "activate" on keypress a CSS button:active style
  • forEach for Uint8ClampedArray
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com