Can you identify the issue with this particular JSON parsing function's reviver?

I am trying to parse a JSON string with a reviver function to only include specific properties. Here is my code snippet:

const whitelist = ['prop1', 'prop2', 'result'];
const reviver = (key, value) => {
  if (whitelist.includes(key)) {
    return value;
  } else {
    return undefined;
  }
};

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

console.log(JSON.parse(theMightyJsonString))
console.log(JSON.parse(theMightyJsonString, reviver))

Although I can successfully parse the JSON string using JSON.parse(theMightyJsonString), the result is undefined when using

JSON.parse(theMightyJsonString, reviver)
. What could be causing this issue?

Answer №1

When the last call to reviver occurs, it will have an empty string as the key "". This enables you to apply a transformation to the final object, such as turning it into undefined. By adding a test for the empty string, the functionality works as expected:

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 ) );

Answer №2

The explanation on how JSON.parse() works states:

When a reviver is utilized, the parsed value is transformed before being returned. This transformation applies to the computed value and all its properties, starting from the deepest nested properties to the original value itself.

The phrase "and proceeding to the original value itself" addresses your query. The reviver function in JSON.parse() iterates through the keys 'prop1', 'prop2', 'prop3' along with their corresponding values, then moves on to the key 'result' and its value (an object), and finally processes an empty string as a key and the entire parsed object as the value.

The documentation also offers a solution to your issue:

If the reviver selectively transforms values and leaves others untouched, make sure to return all unaltered values as-is, or else they will be omitted from the final object.

Your code should be structured as follows:

const whitelist = ['prop1', 'prop2', 'result'];
const reviver = (key, value) => {

  if (key === '' || whitelist.includes(key)) {
    return value;
  } else {
    return undefined; // delete the key explicitly
  }
};

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

console.log(JSON.parse(theMightyJsonString))
console.log(JSON.parse(theMightyJsonString, reviver))

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

Using PHP to send a JSON request via cURL

I am attempting to make a cURL request in PHP. The request I am trying to send is as follows: $ curl -H 'Content-Type: application/json' -d '{"username":"a", "password":"b","msisdn":"447000000001","webhook":"http://example.com/"}' http ...

Allow for the ability to choose a specific option for every individual line that is echoed in

I have researched several similar questions, but none of them address exactly what I am attempting to achieve. My goal is to use AJAX to fetch a PHP page that will display the contents of a folder on my server. Currently, the files are being listed line by ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

Increase the size of a centered image within a table

Lately, I've felt like my mind is starting to unravel. Here's the issue at hand: I've been attempting to resize an image within a table cell so that it spans the full width of the cell. Strangely enough, this seems to be harder than anticip ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

What could be preventing the program from successfully navigating through my @override class?

Having trouble creating multiple markers with longitude and latitude in my Google Maps activity. The code seems to be getting stuck at the @override method, as I keep seeing "jsonParse: is now in json Parse" in the logcat output. However, when I created a ...

Encountered an unexpected comma token while attempting to map an array in ReactJS

Can't figure out why I'm getting an error when trying to map an array in React with the following code: const { loading, error, posts } = this.props; return( {posts.map(onePost => ({ <p key={onePost.id}>{onePost.title}&l ...

In Internet Explorer 11, the input event in VueJS may not be triggered upon the first input

I am working with an input HTML element that has @input="onInput" assigned to it. Within the onInput method, I have console log output set up, specifically I am logging event.currentTarget.value. However, I've noticed a strange behavior in IE11 - whe ...

Discovering the point of exit for a mouse from an image

Visit this website to see the effect in action: I am curious about how the image scrolls into and out of the direction where the mouse enters and leaves. Can you explain how this is achieved? ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Combining JSON-RPC with Swagger for enhanced API documentation and

Currently, I am exploring the idea of incorporating JSON-RPC into my web service using this particular library. Additionally, I am interested in integrating Swagger into my service as well. I find myself contemplating whether these two technologies work s ...

Preserve data on page even after refreshing in Angular

Upon opening my website, I expect to see "Finance/voucher" at the top. However, after refreshing the page, only "Finance" appears which is not what I want. I need it to always display "Finance/voucher" even after a page refresh. I have included all the r ...

Getting specific data from JSON Path extractor with a condition

In need of extracting the value under "currentApproversStr:" when the condition "status":"Ready for Review" is met in the JSON Response body obtained from an HTTP sampler, which will then be passed to another HTTP sampler. Attempted approach that failed: ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Cannot create an instance of 'JSON' using the provided arguments: '(Response<AnyObject, NSError>)' in Swift

Following the upgrade from Xcode 6.2 to Xcode 7.0.1, I encountered this error message. /Users/ZERO/Documents/Xcode/XXXXX/Controllers/LoginViewController.swift:75:35: Cannot invoke initializer for type 'JSON' with an argument list of type & ...

What is the best way to choose an HTML element in React?

Is there a way in React to change the theme value based on localStorage and set it to either light or dark mode? https://i.sstatic.net/Iecsj.jpg I am familiar with using Ref hooks in components, but how can I access a DOM element in the index.html file? ...

Issue with disabling elements using jQuery in IE 10

I'm encountering a problem with using attr('disabled', 'disabled') or prop("disabled", true) in Internet Explorer when using jQuery. This works fine in Firefox and Chrome but not in IE. Any suggestions? I'm attempting to disa ...

Using keys dynamically fetched from a JSON array file to enhance d3js functionality

I am looking to dynamically retrieve keys from an external JSON array and utilize them in d3js functions to create bar charts. Below is the JSON code provided: [ { "Interns": 5, "Projects": 10, "Time":"Jan" }, { "Interns": 16, "Pr ...