Javascript test if is json

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

check if a string is a valid JSON string in JavaScript without using Try/Catch

License

joaquimserafim/is-json

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  border-bottom-style

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

ATTENTION — use try/catch instead that provides you a more resilient approach to check if is a JSON object

Build Status

check if a string is a valid JSON string without using Try/Catch and is a JSON object

*with passObjects = true can pass a JSON object in str , default to false

 var isJSON = require('is-json'); var good_json = '>'; var bad_json = '>'; var str_number = '121212'; console.log(isJSON(good_json)); // true console.log(isJSON(bad_json)); // false console.log(isJSON(str_number)); // false // check is an object var object = ; console.log(isJSON(object, true)); // true // can use isJSON.strict (uses try/catch) if wants something more robust console.log(isJSON.strict('')); // true 

About

check if a string is a valid JSON string in JavaScript without using Try/Catch

Источник

How to test if a string is json or not in Javascript?

In Javascript, it’s common to receive data in the form of a string, but sometimes this data is intended to be parsed as JSON. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It’s important to be able to distinguish between a string that is intended to be parsed as JSON and a string that is not, as attempting to parse a non-JSON string as JSON can result in a runtime error. In this article, we will explore several methods for testing whether a string is valid JSON or not.

Method 1: JSON.parse()

To test if a string is JSON or not using JSON.parse() , you can follow these steps:

  1. Wrap the JSON.parse() method in a try-catch block to handle any errors that may occur when parsing the string.
  2. Inside the try block, pass the string to JSON.parse() method.
  3. If JSON.parse() is able to parse the string without throwing an error, then the string is valid JSON.
  4. If an error is thrown, then the string is not valid JSON.

Here is an example code snippet:

function isJSON(str)  try  JSON.parse(str); return true; > catch (e)  return false; > >

This function takes a string as input and returns true if the string is valid JSON, and false otherwise.

Here are some examples of how to use this function:

isJSON(''); // true isJSON(''); // false (trailing comma) isJSON(''); // true (string value) isJSON(''); // false (trailing comma) isJSON(''); // false (missing quotes around keys) isJSON('null'); // true isJSON('undefined'); // false

Note that this method only checks if the string is valid JSON or not. It does not check if the JSON is well-formed or if it meets any specific requirements.

Method 2: Try-Catch Statement

To test if a string is JSON or not in JavaScript, you can use the Try-Catch statement. Here’s how to do it:

function isJSON(str)  try  JSON.parse(str); > catch (e)  return false; > return true; >

This function takes a string as an argument and returns true if the string is valid JSON, otherwise it returns false.

Let’s break down the function:

  1. We start by using the try keyword to attempt to parse the string as JSON using JSON.parse() .
  2. If there’s an error during parsing, the catch block will be executed and we’ll return false .
  3. If parsing is successful, we’ll return true .

Here are some examples of how to use the function:

// Valid JSON console.log(isJSON('')); // true // Invalid JSON console.log(isJSON(')); // false // Non-JSON string console.log(isJSON('Hello world')); // false

In the first example, the function returns true because the string is valid JSON. In the second example, the function returns false because the string is not valid JSON (missing a closing brace). In the third example, the function returns false because the string is not JSON at all.

That’s it! This is one way to test if a string is JSON or not using the Try-Catch statement in JavaScript.

Method 3: regex

To test if a string is JSON or not using regex in JavaScript, you can use the following code:

function isJSON(str)  if (/^[\],:<>\s]*$/.test(str.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, '')))  return true; > else  return false; > >

This function uses a regular expression to test if the string is valid JSON. Here is a breakdown of the regular expression:

  • /^[\],:<>\s]*$/ matches any string that contains only the following characters: [] , <> , , , : , whitespace.
  • str.replace(/\\[«\\\/bfnrtu]/g, ‘@’) replaces all occurrences of escape characters with the @ symbol.
  • str.replace(/»[^»\\\n\r]*»|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ‘]’) replaces all JSON values with the ] symbol.
  • str.replace(/(?:^|:|,)(?:\s*\[)+/g, ») removes all empty arrays.

If the resulting string matches the regular expression, then the original string is valid JSON. Here are some examples of how to use this function:

isJSON(''); // true isJSON(''); // false isJSON(''); // true isJSON(''); // false isJSON('[1, 2, 3]'); // true isJSON('[1, 2, 3,]'); // false isJSON(''); // true isJSON(''); // false isJSON(']>'); // true

In conclusion, this function can be used to test if a string is valid JSON using regex in JavaScript.

Источник

How to test if a string is json or not in Javascript?

In Javascript, it’s common to receive data in the form of a string, but sometimes this data is intended to be parsed as JSON. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It’s important to be able to distinguish between a string that is intended to be parsed as JSON and a string that is not, as attempting to parse a non-JSON string as JSON can result in a runtime error. In this article, we will explore several methods for testing whether a string is valid JSON or not.

Method 1: JSON.parse()

To test if a string is JSON or not using JSON.parse() , you can follow these steps:

  1. Wrap the JSON.parse() method in a try-catch block to handle any errors that may occur when parsing the string.
  2. Inside the try block, pass the string to JSON.parse() method.
  3. If JSON.parse() is able to parse the string without throwing an error, then the string is valid JSON.
  4. If an error is thrown, then the string is not valid JSON.

Here is an example code snippet:

function isJSON(str)  try  JSON.parse(str); return true; > catch (e)  return false; > >

This function takes a string as input and returns true if the string is valid JSON, and false otherwise.

Here are some examples of how to use this function:

isJSON(''); // true isJSON(''); // false (trailing comma) isJSON(''); // true (string value) isJSON(''); // false (trailing comma) isJSON(''); // false (missing quotes around keys) isJSON('null'); // true isJSON('undefined'); // false

Note that this method only checks if the string is valid JSON or not. It does not check if the JSON is well-formed or if it meets any specific requirements.

Method 2: Try-Catch Statement

To test if a string is JSON or not in JavaScript, you can use the Try-Catch statement. Here’s how to do it:

function isJSON(str)  try  JSON.parse(str); > catch (e)  return false; > return true; >

This function takes a string as an argument and returns true if the string is valid JSON, otherwise it returns false.

Let’s break down the function:

  1. We start by using the try keyword to attempt to parse the string as JSON using JSON.parse() .
  2. If there’s an error during parsing, the catch block will be executed and we’ll return false .
  3. If parsing is successful, we’ll return true .

Here are some examples of how to use the function:

// Valid JSON console.log(isJSON('')); // true // Invalid JSON console.log(isJSON(')); // false // Non-JSON string console.log(isJSON('Hello world')); // false

In the first example, the function returns true because the string is valid JSON. In the second example, the function returns false because the string is not valid JSON (missing a closing brace). In the third example, the function returns false because the string is not JSON at all.

That’s it! This is one way to test if a string is JSON or not using the Try-Catch statement in JavaScript.

Method 3: regex

To test if a string is JSON or not using regex in JavaScript, you can use the following code:

function isJSON(str)  if (/^[\],:<>\s]*$/.test(str.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, '')))  return true; > else  return false; > >

This function uses a regular expression to test if the string is valid JSON. Here is a breakdown of the regular expression:

  • /^[\],:<>\s]*$/ matches any string that contains only the following characters: [] , <> , , , : , whitespace.
  • str.replace(/\\[«\\\/bfnrtu]/g, ‘@’) replaces all occurrences of escape characters with the @ symbol.
  • str.replace(/»[^»\\\n\r]*»|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ‘]’) replaces all JSON values with the ] symbol.
  • str.replace(/(?:^|:|,)(?:\s*\[)+/g, ») removes all empty arrays.

If the resulting string matches the regular expression, then the original string is valid JSON. Here are some examples of how to use this function:

isJSON(''); // true isJSON(''); // false isJSON(''); // true isJSON(''); // false isJSON('[1, 2, 3]'); // true isJSON('[1, 2, 3,]'); // false isJSON(''); // true isJSON(''); // false isJSON(']>'); // true

In conclusion, this function can be used to test if a string is valid JSON using regex in JavaScript.

Источник

How to check if the object type is JSON in javascript

It is a short tutorial about how to check an object in JSON in javascript and typescript.

JSON is simple data with keys and values enclosed in parentheses.

JSON objects don’t have type representation in javascript, They treat as normal strings.

Sometimes, We might think and need to answer the below questions for

  • Check whether a string is a valid json object or not
  • Find an Object in json format
  • String variable is json parsable or not

How to check object variable is JSON in javascript

  • Javascript has a JSON class that has a parse method to convert a string into an object.
  • Enclose the parse method in the try and catch block
  • It throws an error if JSON is not parsable

Here is a function to check string is valid JSOn or not Returns true for valid JSON object, false for invalid JSON data

function isJsonObject(strData)  try  JSON.parse(strData); > catch (e)  return false; > return true; > let jsondata = ''; let notjsondata = "username-admin"; console.log(isJsonObject(jsondata)); // returns true console.log(isJsonObject(notjsondata)); // returns false

Check object type using the npm library

There are many npm libraries to check native object types.

We are going to write an example for the kindOf npm library.

First, install using the npm command.

npm install kind-of --save-dev

Here is a simple program to check types of data

var kindOf = require("kind-of"); console.log(kindOf(12312)); // returns number console.log(kindOf("test")); // returns string console.log(kindOf(false)); // returns boolean kindOf( username: "admin" >); // object

Summary

To Sump up, Learned variable type is JSON object or not using

Источник

Оцените статью