Regular expression to enclose non-quoted values (numbers and boolean) within quotes

I have a JSON file that is valid, but I need to add quotes around the number values and boolean values in order to send this JSON to a wix repeater that requires quotes around them.

If anyone can assist me with this, I would greatly appreciate it.

Example of received JSON:

[{"id":1238890,"category_id":1,"season_id":14866,"venue_id":null,"referee_id":null,"slug":"2022-08-12-melbourne-knights-fc-altona-magic-sc","name":"Melbourne Knights FC – Altona Magic SC","status":"inprogress","time_details":{"prefix":"","initial":0,"max":2700,"timestamp":1660296540,"extra":540}, "_id":1}]

Example of needed JSON:

[{"id":"1238890","category_id":"1","season_id":"14866","venue_id":"null","referee_id":"null","slug":"2022-08-12-melbourne-knights-fc-altona-magic-sc","name":"Melbourne Knights FC – Altona Magic SC","status":"inprogress","time_details":{"prefix":"","initial":"0","max":"2700","timestamp":"1660296540","extra":"540"}, "_id":"1"}]

I attempted the code below to transform the json data, but did not achieve the desired outcome

J'ai essayé ce code là en transformant mon json en chaine string mais sans le résultat escompté..

const regex = /[^"\d,]?(\d+)/g;
const str = [{"id":"1238890","category_id":"1","season_id":"14866","venue_id":"null","referee_id":"null","slug":"2022-08-12-melbourne-knights-fc-altona-magic-sc","name":"Melbourne Knights FC – Altona Magic SC","status":"inprogress","time_details":{"prefix":"","initial":"0","max":"2700","timestamp":"1660296540","extra":"540"}, "_id":"1"}]

const subst = `:` + `"$1"`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Kind regards

Answer №1

To begin, decode the json and then use a replacer function to reformat it (check out MDN for more information). The following code snippet also includes handling of null:

const jsonData = JSON.parse(`[{"id":2534834,"category_id":3,"group_id":11234,"venue_id":null,"ref_id":null,"slug":"2022-12-05-team-a-vs-team-b-game","name":"Team A vs Team B Game","status":"completed","details":{"prefix":"","start":0,"end":2700,"timestamp":1492837400,"additional":540}, "_id":2, "isAvailable":true}]`);
 
console.log(JSON.stringify(jsonData, 
  (key, value) => 
    /number|boolean/.test(typeof value) || value === null ? `${value}` : value, 2));
.as-console-wrapper {
    max-height: 100% !important;
}

Answer №2

Personally, I prefer converting the object instead of resorting to regex

const json = `[{"id":1238890,"category_id":1,"season_id":14866,"venue_id":null,"referee_id":null,"slug":"2022-08-12-melbourne-knights-fc-altona-magic-sc","name":"Melbourne Knights FC – Altona Magic SC","status":"inprogress","time_details":{"prefix":"","initial":0,"max":2700,"timestamp":1660296540,"extra":540}, "_id":1}]`

const data = JSON.parse(json)

const converted = convertToStrings(data)

console.log(converted)

function convertToStrings(obj) {
  if (['boolean', 'number'].includes(typeof obj)) {
    return obj.toString()
  }
  if (obj === null) {
    return 'null'
  }
  if (typeof obj === 'string') {
    return obj
  }
  if (Array.isArray(obj)) {
    const newArray = []
    for (const item of obj) {
      newArray.push(convertToStrings(item))
    }
    return newArray
  }
  if (typeof obj === 'object') {
    const newObj = {}
    for(const key in obj){
      newObj[key] = convertToStrings(obj[key])
    }
    return newObj
  }
  throw new Error('Unsupported property type ' + typeof obj)
}

Answer №3

Like others have mentioned, one method is to convert the JSON string into an object, manipulate the object, and then convert it back to a JSON string.

Alternatively, you can use this concise regular expression to directly modify the JSON string:

const jsonData = '[{"id":1238890,"category_id":1,"season_id":14866,"venue_id":null,"referee_id":null,"slug":"2022-08-12-melbourne-knights-fc-altona-magic-sc","name":"Melbourne Knights FC – Altona Magic SC","status":"inprogress","time_details":{"prefix":"","initial":0,"max":2700,"timestamp":1660296540,"extra":540}, "_id":1, "someBoolean":false}]';
const regex = /(":\s*)(\d+|true|false|null)(,\s*"|\s*[\}\]])/g;
console.log(jsonData.replace(regex, '$1"$2"$3'));

Here's a breakdown of the regular expression used:

  • (":\s*) -- captures the pattern before the values that need to be escaped
  • (\d+|true|false|null) -- captures the values that need to be escaped
  • (,\s*"|\s*[\}\]]) -- captures the pattern after the values that need to be escaped
  • /g -- allows for multiple replacements in the string

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

The error handler in AngularJS is failing to run

Currently I am utilizing angularJS and spring 3.2.4 to handle REST exceptions in a particular way, shown below: @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value=HttpStatus.BAD_REQUEST) @ResponseBody public Err ...

Vitest React Redux - anticipating that the "spy" will be invoked with certain arguments

When testing my React application that utilizes Redux, I encountered an error with my thunk function for registering users. The specific error message I received was: "AssertionError: expected 'spy' to be called with arguments: [ [Function] ]" // ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

Reading S3 files in Lambda functions using Python: A complete guide

Currently, I am attempting to retrieve a file from S3 that contains the following data: {"empID":{"n":"7"},"name":{"s":"NewEntry"}} {"empID":{"n":"3"},"name":{"s":"manish"}} {"empID":{"n":"2"},"name":{"s":"mandeep"}} {"empID":{"n":"4"},"name":{"s":"Vikas" ...

The error message angular.js:12408 is indicating a syntax error with ng-pattern in the $parse function

Here is the code I am working on: <input ng-required="{{ ixarisCurrOpts[0].selected }}" ng-pattern="[0R]{2}[a-zA-Z0-9_-]{23}" ng-click="returnFundAccGBP()" ng-focus="fFundAccGBP=true" ng-change="returnFundAccGBP()" ng-blur="fFundAc ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

autoNumeric JS field text is cleared upon losing focus

While implementing autoNumeric js for thousand separation, I noticed that after entering a value and then focusing out to another field, the entered value gets erased. What could be causing this issue? Below is the code I used: jQuery("#job_no").autoNu ...

Next.JS reported that it "Executed a greater number of hooks compared to the previous render"

Currently, I am utilizing useSWR to fetch data from my express and mongo-db backend. The retrieval of data from the database is successful without any issues. Below is the code snippet that allowed me to do this: //SWR method for hydration const fetcher = ...

"Encountering an unidentified custom element in Vue 2 while exploring Vue libraries

In my Vue project, I have integrated libraries like FusionCharts and VueProgressBar. However, I encountered an error in my console: Unknown custom element: <vue-progress-bar> - did you register the component correctly? For recursive components, make ...

What is the best way to access data from outside a forEach loop in JavaScript?

I am trying to access the value of my uid outside of the foreach loop in my code. Can anyone assist me with this? This is the code I am working with: var conf_url = "https://192.168.236.33/confbridge_participants/conference_participants.json?cid=009000 ...

How can I resolve the error message "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" to successfully display my data?

When I send an ajax request to iterate over multiple arrays, I encounter the following error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in $.get(url).done(function(data){ var data = JSON.stringify(data); v ...

Trouble with jQuery UI add/remove class duration feature

I have implemented Jquery UI with the addClass/removeClass function successfully. However, I am facing an issue where the class changes without the specified duration. Below is the relevant code snippet: <script src="https://ajax.googleapis.com/ajax/li ...

Using Javascript code to draw particles at the cursor's position and then directing those particles towards the bottom of

I found an interesting JavaScript code snippet that creates a bubble particles effect around the cursor. You can download it from https://github.com/tholman/90s-cursor-effects. However, I encountered a problem when adding certain elements inside a specifi ...

Navigating without the need for a mouse click

Is there a way to automatically redirect without user interaction? I need the redirection to happen without clicking on anything <script> setInterval(function(){ window.location.replace("http://your.next.page/"); }, 5000); // Redirec ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

The knockout.js subscribe function isn't activating during the initial set

In my model class, I have defined observables and I am looking to subscribe to their sets. Below is the code snippet that showcases what I currently have: var dto = function (data) { var self = this; self.Value1 = ko.observable(data.Value1); s ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Error occurs while attempting to return a JSON record using an Ajax request

As I am still new to the concept of MVC and Ajax, please bear with me while I try to understand how they work together to fetch data from a database. I encountered the following error: parse error syntax error Unexpected token < [object, object] wh ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

Display or conceal fields depending on custom object specifications

I am attempting to centralize my show/hide functionality for fields in one object (like vm.foo) that contains key-value pairs. For example, I could add another pair like 1502: true to hide a field with the key 1502. Is there a way to pass variables from t ...