Despite my attempts to assign null as a value to the key named null, the result continues to be undefined

I created a custom parseJSON function that is intended to produce the same result as JSON.parse when given the same input. There's also a helper function named getParsed() that correctly parses strings into their respective data types. However, I've encountered an issue:

parseJSON('{"boolean, true": true, "boolean, false": false, "null": null }')
// currently outputs
{boolean, true: true, boolean, false: false, null: undefined}

What I actually need is for the last property to be returned as

null: null

to align with the output of JSON.parse()

I suspect there is some detail about null that I might be overlooking here, but I haven't been able to resolve this issue. Please find the code snippet below (at the moment, the function only handles object literals).

var getParsed = str => {
  // Check if string is a number (floating point or integer)
  if (/^-?\d*\.?\d+$/.test(str)) {
    if (str.includes('.')) {
      return parseFloat(str);
    } else {
      return parseInt(str);
    }
  }
  // Check if string is enclosed in quotes (will remain as a string)
  if (/"[^"]*()[^"]*"/.test(str)) {
    var arr = str.split('');
    arr.pop();
    arr.shift();
    return arr.join('');
  }
  // Check if string represents a boolean value
  if (str === 'true') { return true; }
  if (str === 'false') { return false; }
  // Check if string is null or undefined
  if (str === 'null' || str === 'undefined') { return null; }
};



var parseJSON = function (json, invoked = false) {
  if (json.startsWith('{')) {
    var arr = json.split('');
    var first = arr.shift();
    var last = arr.pop();
    var props = arr.join('').split(', ');
    var res = {};

    for (var i = 0; i < props.length; i++) {
      if (!props[i].includes(':')) {
        props[i] = props[i] + ', ' + props[i + 1];
        props.splice(i + 1, 1);
      }
    }

    for (var i = 0; i < props.length; i++) {
      var prop = props[i].split(': ');
      var key = prop[0];
      var val = prop[1];

      if (key.includes('"')) {
        key = key.split('');
        key.shift();
        key.pop();
        key = key.join('');
        res[key] = getParsed(val);
      }
    }

    return res;
};

Answer №1

Try adding the following code snippet at the beginning of the getParsed function:

console.log({str: str, test: (str === 'null')})

After doing this, you should see output like this:

{str: 'null ', test: false}

This means that the final test in your function was failing because of the extra space in the string. Since the function didn't return anything, you were ending up with an undefined value in the final object.

To fix this issue, make sure to remove any unnecessary spaces and it should work perfectly :)

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

Adjust mesh tessellation level using scroll control

On this page (), you can see how the meshes forming the text continuously come together and then separate in a loop, as demonstrated in the source code here: https://github.com/mrdoob/three.js/blob/dev/examples/webgl_modifier_tessellation.html. I am inter ...

Enhance the variety of types for an external module in TypeScript

I am in the process of migrating an existing codebase from a JavaScript/React/JSX setup to TypeScript. My plan is to tackle this task file by file, but I have a question regarding the best approach to make the TypeScript compiler work seamlessly with the e ...

Having trouble receiving a JSON array after making an Ajax request

I have read through previous posts on this issue, but I still can't seem to figure it out. Hopefully, someone here can help me solve this problem. My challenge lies in retrieving an array, which I have encoded in json, from a PHP script and passing i ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...

Using Mongoose to delete multiple documents with the "like" operator

I am looking to remove all documents from a MongoDB collection that have a particular string in one of the fields. (I am working with mongoose) In SQL terms, the equivalent query would be: DELETE FROM users WHERE name LIKE '%test%' ...

Using React to retrieve information from a .json file and comparing it against user input

I'm currently working on a Covid dashboard and I would like to incorporate a JSON file into it. However, the way the data is structured within the file is causing me some difficulties. https://i.sstatic.net/PiqCm.png Within the "airport" name field, ...

Is it possible to enable tab navigation for a button located within a div when the div is in focus?

I have a component set up like this: (Check out the Code Sandbox example here: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js) https://i.sstatic.net/ZuxdL.png The section highlighted in green is a div. Here is the code snippet: import { ...

What is the reason for choosing the term "shadow" over "override" in JavaScript?

Despite my initial assumptions, I found myself unable to discover a definitive answer through numerous Google searches on this topic. This question pertains to the use of the class pattern in Ecmascript 6 and beyond. I initially believed that method over ...

Enforcing JSON data type in PostgreSQL

Is there a method to guarantee that the input JSON data contains specific elements, specifically the id and name values? I am not referring to primary elements, but rather making sure that any JSON being inserted has at least these two key-value pairs. The ...

I'm currently working on incorporating an edit feature into the create form by utilizing server actions in the latest version of Next.js, version 14

The issue arises when the create form's type (id) parameter is null, which does not align with prisma's (edit info). export function AboutForm({ id }: { id: number }) { const router = useRouter(); const [err, setErr] = useState("&qu ...

The integration of AngularJS with Bootstrap 3 accordion seems to encounter issues when included through ng-view

Here's the issue: When using the accordion in a view loaded with the ng-view directive, the accordion title clicks stop working correctly. Check out this demo for an example However, when the accordion is used directly on the page without ng-view, i ...

Tips for updating mongoose user data with associated posts that share the same user id

As I dive into building my inaugural MERN application, a particular issue has arisen. The posts within the application contain the user id information: { "reward": { ... }, "_id": "5eb2d90d7d56c415cc4d5f97", "user": "5eabbb85b8814 ...

The navigation on my mobile collapses whenever I use the Hello bar app

I am facing a problem with my Shopify theme. I recently installed an app called "Hello Bar" to show offers on all pages, but it seems to be incompatible with my theme. The developers of the app suggested adding the following code to my CSS file: @media ...

Sending an Array from a ReactJS Frontend to a Django Backend using JavaScript and Python

I successfully created a website using Django and React JS. In my project, I am working on passing an array named pict from the frontend JavaScript to the backend Python in Django. let pict = []; pictureEl.addEventListener(`click`, function () { console ...

Finding the IST date time (YYYY-MM-DD HH:mm:ss) in a Node.js environment is a common requirement. Let's

I recently used the code below to retrieve the current time and date in IST: const x = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '') Output: 2020-09-01 17:49:48 However, I actually need to obtain the time in IST ...

Struggling to choose between PHP and jQuery for handling GET requests

I've been attempting to pass two variables from an HTML page to a PHP script, but I'm consistently receiving a response in text/html format. Essentially, the entire PHP code is being returned to the console. Here's the jQuery code I'm ...

Grouping of elements, text, and combining with .join( )

Seeking advice from a newcomer... I am attempting to develop a function that takes an array and an empty string as parameters. The function should use the .join() method on the array and assign the result to the empty string provided. Although the functi ...

PHP/JSON formatting

My goal is to populate a dropdown menu with entries from MySQL using a technique I found in this particular answer. It's functioning well - when an event is selected, a new dropdown appears with the dates that event is scheduled for. But now, I also ...

Prevent submission until all form fields are filled with data

I need help fixing the issue I'm having with disabling the submit button until all input fields have some data. Currently, the button is disabled but remains that way even after all inputs are filled in. What could be causing this problem? $(docume ...