Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
JSON.parse() reviver function: How to access to a higher level object

JSON.parse Reviver function: Access to object being revived?

Reading this one, I tried the code below to get the full object that is containing the property that I specified.

let aTestStr = '{
  "prop1": "this is prop 1", 
  "prop2": {
    "prop2A": 25, 
    "prop2B": 13, 
    "prop2C": "This is 2-c"
  }
}';
let aTestStr = '{"prop1": "this is prop 1", "prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}}';
let aTestObj = JSON.parse(aTestStr, function(key, value) {
  //at this point, 'this' refers to the object being revived
  //E.g., when key == 'prop1', 'this' is an object with prop1 and prop2
  //when key == prop2B, 'this' is an object with prop2A, prop2B and prop2C
    if (key == "prop2B") {
      // the object being revived('this') is an object named 'prop2'
      // add a prop to 'this'
      this.prop2D = 60;
      console.log(this);
    }
});

It would return:

{prop2B: 13, prop2C: 'This is 2-c', prop2D: 60}
  1. I guess it omits the prop2A property because this is detected after the conditional finds prop2B..? I would appreciate to know why, and how to get access to the full object.

  2. Also if you have some time, can you explain how to get access to the higher level than this? For example, is there a way to print out prop2(the name of this) from the conditional if (key == "prop2B") in reviver function?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For question #1 it's because you don't return anything from your reviver, so the object actually looses its properties that have already been parsed.
Simply add return value at the end of your reviver to have the "full" object.

let aTestStr = '{"prop1": "this is prop 1", "prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}}';
let aTestObj = JSON.parse(aTestStr, function(key, value) {
  if (key == "prop2B") {
    this.prop2D = 60;
    console.log(this);
  }
  return value;
});

And regarding #2, this isn't possible. JSON.parse() reviver visits the values from leaves to root, so the parent never appeared in the reviver before all its children values have been parsed.
The best here is probably to simply walk back your object after revival.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!