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:

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

Is there a way to gradually reveal JSON data without continuously re-parsing and displaying it on a webpage?

Currently, I am working with a log file that is constantly updated by a running script in real-time. My goal is to effectively monitor the status of this script on a web page using HTML and JavaScript. To achieve this, I have utilized JavaScript to dynamic ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Tips for speeding up the loading of JSON with large data on HTTP requests or webpages

When requesting the page (via HTTP or webpage), it seems to be very slow and even crashes unless I load my JSON data with fewer entries. This issue is critical as I anticipate needing to work with large amounts of data frequently in the future. Below are t ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

Is there a way to send a multi-dimensional array using jQuery ajax?

I am encountering an issue with posting an array as a JavaScript variable {{0,0},{1,1},{2,2}} using JSON.Stringify. Whenever I try to post it, I receive an internal server error 500. Can someone please advise on how I can successfully post and utilize this ...

Storing information in a database using Phantomjs

My app is built on phantomjs and here's how it currently operates: 1. A php script retrieves data from my postgres database as an array, 2. The array of data is then passed as an argument to a shell_exec command running a phantomjs script, 3. Phantomj ...

Update the parent node in the Google Org Chart

This is my first time working with Google Charts and I have a couple of questions: Is there a method in the API to update the parent of an existing node? I am facing a challenge where I need to build a tree structure top-down, which means that I know the ...

Decoding a Json containing a JsonArray at its root with the help of Retrofit

I have a Json file with an array as a node, which is causing some issues for me. I am not very familiar with Retrofit and I'm struggling to understand how to resolve this problem. [ { "first_name":"Jakub", "nickname":"", "last_name":"Mach ...

Using JavaScript to Filter JSON Objects

After making a php ajax call, I have received the following JSON data that needs to be displayed to the users: JSON {"headers":{},"body":"{\"comuni\":[{\"datapresub\":\"08\/08 ...

Issue with continuous loader malfunction

I integrated a 3-second mini-loading animation on my website. It shows up every time I refresh the site or navigate to another page. The issue I'm facing is that once I add the loading section, it never stops (it should only last for 3 seconds). Usua ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

Encountering a malfunction while executing an npm command specified in the package.json file

Currently, I am following a tutorial on Node, React, and Express on Udemy. In the tutorial, when I execute the command npm run data:import I encounter the following error: undefined npm ERR! code ELIFECYCLE npm ERR! errno 1 ...

JS - What is causing my JavaScript src to not work properly?

Here is a snippet of my code: <form name="calculator"> <input type="button" name="latest" value="You are not using the latest version."> <script src="http://www.alvinneo.com/bulbuleatsfood.js"> if(latest-version==="1.0.4.2"){ document.ca ...

Leveraging the power of Fractal Transformer in conjunction with ember-data

While using the PHP league's Fractal as the transformer for my API, I have encountered an issue where the item transformer is wrapping everything in an array similar to a collection. This goes against the standards set by the JSON API. For instance, ...

How can I troubleshoot email validation issues in Vue.js?

<button type="submit" class="register-button" :class="(isDisabled) ? '' : 'selected'" :disabled='isDisabled' v-on:click=" isFirstScreen ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...