The importance of using a reviver function in JSON.parse for handling nested

I am working on customizing the JSON.parse function by using the optional reviver argument to specify that I want the calc(string) function to focus on a key named "expr" within the input string. Once that key is processed, the function should then operate on the remaining portion of the string.

However, whenever I run this code, I keep receiving a NaN result.

Interestingly, if I disable the last two calls to calc(string) just before the console.log(initNumber) statement, the program performs as intended.

In essence, I want the function to recognize the key "expr" and carry out specific operations based on the nested "op" key within it. For example, if the "op" key has a value of "add", the function should execute the add() function on the nested object. The same principle applies if the "op" key is "subtract".

Any assistance would be greatly valued.

var initNum = 0;

var calc = function(string) {
    var calcString = JSON.parse(string, reviver);

    add(calcString);
    subtract(calcString);
};

var add = function(string) {
    if (string["op"] == "add") {
    var numString = parseInt(JSON.stringify(string["number"]));
    initNum = numString + initNum;
    return initNum;
  }
}
var subtract = function(string) {
    if (string["op"] == "subtract") {
    var numString = parseInt(JSON.stringify(string["number"]));
    initNum = initNum - numString;
    return initNum;
  }
}

var reviver = function(key, val) {
  if (key == "expr") {
    if (val.op == "add") {
      return add(val);
    }
    else if (val.op == "subtract") {
      return subtract(val);
    }
  }
    else {
      return val;
    }
};

calc('{"op" : "add", "number" : 5}');
calc('{"op" : "subtract", "number" : 2}');
calc('{"op" : "add", "number" : 19}');
calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
calc('{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}');
console.log(initNum);

Answer №1

Here are a few key points to consider:

  • reviver will provide you with pre-parsed values, eliminating the need to parse them again.
  • If you convert an expr into a value, your add and subtract functions must be able to interpret those values, not just number. This could lead to different logic. Hence, the approach of obtaining the operand as demonstrated below. It's important to acknowledge the possibility of there not being a number argument and address this scenario.
  • The reason you were encountering NaN was due to the above-mentioned issue. You were trying to extract the number from objects that did not have one (results of reviving exprs), resulting in undefined values that disrupted the calculations.

Remember that

{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}

transforms into

{"op": "subtract", "expr" : 37}

after reviving the expression, so it's crucial to address this scenario.

var initNum = 0;

var calc = function(string) {
    var calcObj = JSON.parse(string, reviver);

    add(calcObj);
    subtract(calcObj);
};

var add = function(obj) {
    if (obj["op"] == "add") {
      var operand = (obj["number"])? obj["number"] : obj["expr"];
      initNum = operand + initNum;
      console.log("running total : "+initNum);
      return initNum;
  }
}
var subtract = function(obj) {
    if (obj["op"] == "subtract") {
      var operand = (obj["number"])? obj["number"] : obj["expr"];
      initNum = initNum - operand;
      console.log("running total : "+initNum);
      return initNum;
  }
}

var reviver = function(key, val) {
  if (key == "expr") {
    if (val.op == "add") {
      return add(val);
    }
    else if (val.op == "subtract") {
      return subtract(val);
    }
  }
    else {
      return val;
    }
};

calc('{"op" : "add", "number" : 5}');
calc('{"op" : "subtract", "number" : 2}');
calc('{"op" : "add", "number" : 19}');
calc('{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}');
calc('{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}');
console.log(initNum);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging client API callback variables within a Node.js backend system

If I send a request on the client side using the code snippet below public/foo.js function bar() { fetch('https://api.github.com/') .then(response => response.json()) .then(data => { console.log(data) }) .catch( ...

Vue: Implement out-in transition where the incoming element appears before the outgoing element has completely disappeared

Check out my code on Codepen: here In this scenario, I have set up two div elements: Block 1 and Block 2. The functionality I am looking for is when a button is clicked, Block 1 smoothly translates to the left until it goes out of view. Once that happens ...

What is the best way to populate a dropdown menu by matching keys from an array within an ng-repeat

My JSON structure looks like this: 101 : "List": [ { "Name": "Pink" }, { "Name": "Black" } ] 102 : "List": [ { "Name": "Red" }, { "Name": "Yellow" } ] $sco ...

The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality it ...

Tips for verifying the presence of a specific key in a JSON post request and modifying the JSON file using Node.js

I am currently developing an API to determine the online status of a Minecraft server. In my implementation, I am utilizing express and bodyParser with a JSON file for storing the server's status information. My goal is to validate that the POST reque ...

Determine if checkboxes exist on a webpage using jQuery

I am facing a situation where a form is dynamically loaded via ajax. Depending on the parameters passed to retrieve the form, it may or may not contain checkboxes. I am looking for a way to verify the presence of checkboxes on the page and prompt the user ...

What is the correct way to integrate a new component into my JHipster + Angular project while ensuring that the routerlink functions properly?

After creating a new application on JHipster, I wanted to add a FAQ page to my web portal. However, the default CRUD components generated by JHipster made it look more like an admin/user view table. I needed to make the FAQ page accessible to visitors with ...

How is UI Router Extras causing unexpected errors in my unit tests?

QUESTION: - I am facing failures in my tests after installing ui-router-extras. How can I resolve this issue? - Is there a way to use ui-router-extras without causing test failures? If you want to quickly install this, use yeoman along with angular-full ...

A command-line style text input box in HTML

I am currently developing a unique text box that enables the execution of custom commands using a customized syntax. This concept is intended to help teach programming to children. For example, when a user types a $ sign, the program responds with an aler ...

React components receive props as an empty array when they are being passed to the component

I am passing a state to a component as a prop in the following way: componentDidMount() { axios.get("path/to/data") .then(result => { this.setState({ receivedData: result.data, }); ...

Encountered an error in production mode with Angular 7: Uncaught ReferenceError - "environment" variable

During development, my application runs smoothly, and ng build --prod --source-map successfully compiles the application. However, when attempting to access it through the browser, an error occurs: app.module.ts:47 Uncaught ReferenceError: env is not defi ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Effortlessly handle form submission with jQuery AJAX, automatically redirecting upon successful

I am working on a project using ASP.Net MVC where I have a view that submits form data to a controller action. In order to make this form submission more dynamic, I am trying to utilize jQuery to post the form via an AJAX call with the following code: $(" ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

Iterate through every item in Google Docs and duplicate them onto a fresh page

I am currently developing a script that allows teachers to easily create translations of documents stored on Google Drive. The script is expected to go through the body elements of the document, translate the text, and paste it onto a new page appended to ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Exploring Data and Models within AngularJS

I am working on a WebApp that has a unique HTML layout Nav-column-| Center Column---- | Right Column Link1---------|Data corresponding|Data Corresponding to Link1-A Link2---------| to Nav-column------| (ie based oon Center Column Link) Link3----- ...

JavaScript Discord bot encounters an issue: .sendMessage function is not recognized

Currently, I am developing a bot and testing its messaging functionality using .sendMessage method. (I prefer the bot not to send messages upon receiving any input, hence avoiding the use of: bot.on("message", function(message) {}); However, I am encoun ...