Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org:

https://i.sstatic.net/JKW9V.gif

Here is the regex I have come up with so far:

/^\"((?=\\)\\(\"|\/|\\|b|f|n|r|t|u[0-9a-f]{4}))*\"$/

This regex successfully matches instances where there is a backslash followed by a character and an empty string. However, my dilemma lies in incorporating UNICODE characters.

Is there a regex pattern that can identify any UNICODE character excluding " or \ or control characters? Will it also detect a newline or horizontal tab?

I noticed that while the regex matches the string "\t", it does not recognize " " (four spaces meant to signify a tab). While extending the regex is an option, my hunch is that the horizontal tab is a UNICODE character.

Credit goes to Jaeger Kor for updating my regex to the following:

/^\"((?=\\)\\(\"|\/|\\|b|f|n|r|t|u[0-9a-f]{4})|[^\\"]*)*\"$/

This revised regex seems accurate, but should I be checking for control characters separately? Or is this unnecessary considering they fall under non-printable characters as per regular-expressions.info? The input being validated always originates from a textarea.

As an update, here is the finalized regex for reference:

/^("(((?=\\)\\(["\\\/bfnrt]|u[0-9a-fA-F]{4}))|[^"\\\0-\x1F\x7F]+)*")$/

Answer №1

If you have a specific question, you can create a character class for it:

# Use this to match any character except \ or "
/[^\\"]/

You can then add * at the end for zero or unlimited occurrences, or use + for one or more:

/[^\\"]*/

Another option is provided below, found on https://regex101.com/ under the library tab when searching for json:

/(?(DEFINE)
# This regex defines atomic patterns for JSON without backtracking
(?<json>(?>\s*(?&object)\s*|\s*(?&array)\s*))
(?<object>(?>\{\s*(?>(?&pair)(?>\s*,\s*(?&pair))*)?\s*\}))
(?<pair>(?>(?&STRING)\s*:\s*(?&value)))
(?<array>(?>>\[\s*(?>(?&value)(?>\s*,\s*(?&value))*)?\s*\]))
(?<value>(?>>true|false|null|(?&STRING)|(?&NUMBER)|(?&object)|(?&array)))
(?<STRING>(?>>"(?>\\(?>["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\0-\x1F\x7F]+)*"))
(?<NUMBER>(?>>-?(?>0|[1-9][0-9]*)(?>.\.[0-9]+)?(?>[eE][+-]?[0-9]+)?))
)
\A(?&json)\z/x

This regex matches any valid JSON format and can be tested on the website mentioned above.

EDIT:

Link to the regex

Answer №2

Try using this regular expression, which can also handle arrays of JSON objects:

((\[[^\}]{3,})?\{s*[^\}\{]{3,}?:.*\}([^\{]+\])?)

Check out the demo here: https://regex101.com/r/aHAnJL/1

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

Incorporating a File Attachment within a JSON Structure

Can a file attachment be included in a JSON Object? I am working on an HTML Form with text field inputs and a file attachment, and I would like to send all this form data (including the file attachment) as a JSON Object to the server. Are there any specif ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Node.js application experiences a delay when calling Mongoose Model.save()

I've been delving into the realms of node and mongo in order to construct a basic web application while also expanding my knowledge on web development. However, I'm encountering an issue when it comes to calling Model.save(); the continuation fun ...

Guide on enabling users to input slide number and URL address to load content using Ajax

Is there a way to customize the number of slides in a slider and choose which content is loaded into each slide using AJAX calls in jQuery? Currently, my slider uses the jQuery .load() method to dynamically load content into each slide when it becomes vis ...

Simplify your code with promises in JavaScript

Running on an API with node v6.3.0, I have the following code that executes two separate promises based on a conditional check for a parameter in a POST request. if (paramExists) { // query database with this condition User.filter(/* utilize param ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

What is the jQuery syntax for targeting a specific element within an object?

Is there a way to access a sub element from $(this)? For instance, how can I specifically select a span element inside the this object? ...

Tips on avoiding duplicate selection of checkboxes with Vue.js

Recently delving into vue.js, I encountered a challenge with multiple checkboxes sharing the same value. This resulted in checkboxes of the same value being checked simultaneously. How can this issue be resolved? var app = new Vue({ el: '#app&apo ...

Is it possible for me to include a variable with the xmlhttp response text?

There is a function defined as follows: function call_view_details(viewid) { view_details(viewid); setInterval(function(){view_details(viewid)},5000); } which I invoke when the page loads. Its main purpose is to set intervals for view_details(). ...

Why am I unable to "append a list" or "update a dictionary" while parsing through the lines of a text file?

Here is a snippet from my text file: "aroint" : "Lorem.", "agama" : "Simply.", "allantoidea" : "Dummy.", "ampelopsis" : "Whiske"\"red.", "zopilote" : & ...

Is it possible to retrieve a local variable from a JavaScript function and utilize it outside of its

I've been struggling for hours to access a local variable outside of a function, but I can't figure out where I went wrong. Here's the code: Here's my edited code: if (lastMsg.toUpperCase().indexOf("@TEST") > -1) { var myPy ...

Top method for identifying "abandoned words" within text that has been wrapped

Our content and design teams have a specific request to prevent paragraphs from ending with an "orphan word" - a single word on the last line of text that has wrapped onto multiple lines. The designer's proposed solution is to adjust the margins sligh ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

What is the best way to make this eerie javascript script communicate with my webpage or another jquery file?

I've been struggling with a javascript code that enables infinite scrolling in Tumblr. It seems outdated compared to jQuery, which I'm more familiar with. I've tried integrating this script with my jQuery functions and identifying DOM eleme ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Utilize data from a dynamically loaded component within a parent component in Vue.js

In my Vuejs application, I've implemented a wizard-type flow with dynamically loaded components. The parent component contains the Save button, while the child components have all the text fields. Upon clicking the Save button, I need to achieve two m ...