Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation.

isJSON = async(str) => {
  try {
    return (JSON.parse(str) && !!str);
  } catch (e) {
    return false;
  }
}

var testJSON = '{"name": "foo"}'
var number = 22
console.log("result is : ", isJSON(testJSON))
console.log("result is : ", isJSON(number))

The variable str holds the input value and this function checks if the value is of json type or not. However, it returns true even for numeric input values like str=22. My intention is to only check if the input value is in the json format. Can you help me resolve this issue?

Answer №1

JSON.parse function will automatically convert values to strings.

To ensure that the value is indeed a string, you can perform a simple check.

if (typeof str !== "string") return false;

The text "22" is considered a valid JSON string.


If your goal is to verify not only if the value is in JSON format but specifically a representation of a non-array object, then you need to implement additional checks.

isObjectAsJSON = (str) => {
  if (typeof str !== "string") return false;
  try {
    const parsed = JSON.parse(str);
    if (typeof parsed !== "object") return false;
    if (Array.isArray(parsed)) return false;
    return true;
  } catch (e) {
    return false;
  }
};

const sampleValues = {
  number: 22,
  json_number: JSON.stringify(22),
  json_array: JSON.stringify(["foo", "bar"]),
  json_object: JSON.stringify({
    foo: "bar"
  }),
};

Object.entries(sampleValues).forEach(([key, value]) => {
  console.log(key, isObjectAsJSON(value))
});

Answer №2

According to https://www.json.org/json-en.html, the sequence of characters "22" qualifies as valid JSON since JSON follows a specific structure where an element is a WS value WS, and the value in this case can be a number.

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

Error: The function bind is not supported on instance[method] in the AdonisJs framework

I am currently integrating the MQTT-adonis module adonis-mqtt response on Git here in my adonis-js application. However, when trying to serve it, an exception is thrown. TypeError: instance[method].bind is not a function Could anyone provide guidance o ...

Unable to retrieve the value of a particular index within an array containing JSON data

Code to add items to an array: var allItems = []; $.getJSON(url, function(data) { $.each(data, function(i) { allItems.push({ theTeam: data[i]["TeamName"], thePlayer: data[i]["TeamPlayer"], }); }); }) When u ...

Tips for Passing Parameters to Vuex mapActions correctly:Executing mapActions in Vuex requires a specific

I am facing an issue with my ProjectPage.vue where I display project issues in a v-data-table. The projects are fetched from a server API call in the sidebar and displayed there. Once I select a project, I want to use its id to retrieve its corresponding i ...

JSON.NET alerts: 'object reference is missing an instance'

Struggling to deserialize a JSON http response, I keep encountering the error "object reference not set to an instance of an object". This issue seems to be common, but none of the solutions I've come across have been effective in resolving it. It fe ...

Obtaining personalized error messages from the backend with express: A step-by-step guide

I'm currently developing a Login App and I'm looking to implement custom error messaging on the Front End. Specifically, I want to display custom error messages when attempting to register with an email that is already in use or when entering a p ...

Struggling with implementing ng-repeat in AngularJS for displaying HTML content

I stumbled upon a post that covers pretty much what I'm trying to achieve: AngularJS - Is it possible to use ng-repeat to render HTML values? Currently, the code appears like this and displays correctly as text: <div ng-repeat="item in items.Item ...

The JSON output seems to be missing from the logcat display

Currently, I am undertaking an online course to learn Android Studio, and I have encountered a problem. The issue arises while developing a weather application utilizing James Smith's Android Asynchronous Http Client dependency. Despite implementing v ...

Having two identical select2 forms on the same page

Integrating two select2 multi-value select boxes into my Rails application is proving to be a challenge. While the top form functions correctly, the bottom one refuses to work as expected. Despite my attempts at changing IDs and adding new JavaScript cod ...

MVC framework's JSON functionality as a replacement for FormCollection

Are there any JSON alternatives for FormCollection to send as a parameter in a POST action? I have a variable number of dynamically generated fields that I need to post back using JSON. ...

What is the process for dynamically populating a select dropdown based on the selection made in another select dropdown?

I need to dynamically populate the second select box based on the option selected in the first select box. Here's what I have tried so far, but it doesn't seem to be working as expected. HTML: <form id="step1"> <p> Creat ...

Collaborative Artistry: Using HTML5, JavaScript, and Node.js for Multiplayer

Creating a multiplayer drawing application for touch-enabled devices has been a challenge. I have utilized Node.js with Socket.io to draw points on a canvas, but there's an issue with the touchend event not resetting properly. To illustrate, take a l ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

The API response does not contain the discounted price information

Getting all the necessary information from different brands and products, such as prices, previous prices, and discounted prices has proven to be a challenging task for me. I am particularly struggling to locate where the price before is displayed. I ca ...

Avoid refreshing the page when adding an item to the cart

I am in the process of creating a online shopping cart and I'm looking for ways to avoid the page from reloading when adding a product to the cart. At the moment, my approach involves using the GET method to add products to the cart. <a href="car ...

At all times, AJAX/PHP/JS will have a readyState of 1 and a Status of 0, with no text response

Recently, I've been attempting to utilize a sample of AJAX to compare form data with an SQL database from a domain at http://www.example.com. However, I'm encountering persistent issues where the readyState remains at 1 and the Status is always 0 ...

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

Getting an undefined error value in the ionic overlay side menu - what could be causing this issue?

My current challenge involves displaying the overlay side menu. I have written code to achieve this, adding a menu icon in the header that opens the overlay side menu when clicked, and closes it when clicked outside. However, I encountered an issue where ...

Stopping video playback when hovering over it

Can anyone help me modify this code so that a video plays only when hovering over it, and stops playing once the hover ends? What changes should I make to the JavaScript portion of the code for this functionality? <div class="padding-box height-40"&g ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...