Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below).

I am in need of a RegEx that can transform JSON into an array containing all characters such as commas, curly brackets for objects, brackets for arrays, colons, escape characters, null values, etc., while disregarding any whitespace.

Pseudocode for the RegEx:

The RegEx should match any curly bracket character (both open and closed), any word enclosed in parenthesis, colon character, comma character, bracket character (both open and closed), numbers, and null values.

Sample Input String (JSON will vary)

{ 
   "hello":"world",
   "\"foo\"":"bar",
   "my_object":{
     "my_array": [
        1,
        null,
        { "my_key":"my_value" }
     ]
   }
}

Desired Output From RegEx

[ 
   "{", "hello", ":", "world", ",", "\"foo\"", ":", "bar", ",", "my_object",":", "{", "my_array", ":", "[", 1, ",", null, ",", "{", "my_key", ":", "my_value", "}", "]", "}", "}"
]

Appreciate your help!

Answer №1

Regular expressions are versatile and can handle various tasks effectively, but I strongly advise against using them with structured data formats such as JSON (or even XML/HTML).

Instead of relying on RegExp for this purpose, consider implementing a recursive function to manipulate the data structure in JavaScript:

const jsdoc = {
  "hello": "world",
  "\"foo\"": "bar",
  "my_object": {
    "my_array": [
      1,
      null,
      {
        "my_key": "my_value"
      }
    ]
  }
}

const parseToArray = obj => {
  var res = [];
  if (Array.isArray(obj)) {
    res.push('[');
    for (entry of obj) {
      var parsed = parseToArray(entry);
      //while (Array.isArray(parsed)) parsed = parseToArray(entry);
      res.push(parsed, ',');
    }
    res.splice(-1);
    res = [...res, ']', ','];
  }
  else if (obj && typeof obj === 'object') {
    obj = Object.entries(obj);
    res.push("{");
    for (entry of obj) {
      res = [...res, entry[0], ":", ...parseToArray(entry[1]), ','];
    }
    res.splice(-1);
    res.push("}");
  } else {
    res = typeof obj === 'string' ? [obj] : obj;
  }
  return Array.isArray(res) ? res.flat() : res;
}

console.log(parseToArray(jsdoc));

IMPORTANT: The method used by this script for handling commas may not be compliant with JSON standards; it could potentially include unnecessary commas in the output. Further refinement is needed to address this issue.

ANOTHER IMPORTANT POINT: This code is more of a proof-of-concept rather than production-ready - it's not optimized and lacks efficiency. There are likely many improvements that can be implemented to enhance its performance. It's important to note that this solution may not scale well without significant modifications. However, it showcases an alternative approach to flattening JSON data that avoids the complexities associated with using regular expressions.

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

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...

Are multiple if statements the key to success or a disaster waiting to happen?

I want to extract specific values from a JSON response that contains information about videos on Wistia. Currently, the JSON response only includes two videos (slatwall.mp4 & igoodworks.mp4) along with their respective data. You can view the JSON HERE. Th ...

Error in Deserialization: Null value encountered

I have integrated the Newtonsoft.Json plugin into my xamarin.forms application to handle serialization and deserialization of an object of type Form public class Form { [JsonProperty("id")] public int id { set; get; } [JsonProperty("title")] ...

Executing Javascript to populate a div element with content based on its CSS class

Is there a way to isolate my View (HTML & CSS files) within a controller like JavascriptCode/AJAX, so that upon page load, only the controller binds the data to a specific element such as a DIV based on its class? Do you think this is achievable? If so, ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

What sets apart .ejs from .html files?

In my Node Js project, all front end files are in .ejs format and call the server.js for backend work. 1) Is there additional functionality provided by ejs compared to html? 2) Does this pertain to expressJs functionality in Node? 3) Can I use angularJs ...

Take the THREE.js matrix data from an object

I am trying to perform matrix multiplication in Three.js. In my code, I have an Object3D and I managed to retrieve the correct matrix by using console.log like so: console.log(scene.getObjectByName("Pointer").matrix) The output looks something like this: ...

Unable to transform dynamically loaded text area into CKEditor

Executing the get_content function upon a link click. function get_content(n) { var hr=new XMLHttpRequest(); var url="./updatecontent.php"; var vars="id="+n; hr.open("POST",url,true); hr.setRequestHeader("Content-type","application/x-w ...

Is there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

Ways to effectively store continuous scale data in a database

I am currently running a straightforward Node.js server (using Express) on my local machine on port 8000. By utilizing the npm package serialport, I have successfully connected to a scale and am able to retrieve its weight in a continuous manner as shown ...

Retrieve information from api and showcase it in html

Recently, I came across an interesting API file that caught my attention: My goal is to extract information from this API and present it on a HTML page in a visually appealing format. Despite scouring various forums, I have yet to find a solution that fi ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

Error encountered in Swift Dark Sky API weather application: Type 'Any' does not contain any subscript members

Currently, I am working on an online tutorial that focuses on reading JSON files. The tutorial instructs us to input the following code: override func viewDidLoad() { super.viewDidLoad() if let url = URL(string: "https://api.forecast.io/forecast/ ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Can one access the method definition within a Visual Studio Code setup for an AngularJS project?

I'm on a quest to locate the method definition within my AngularJS project, but alas, I am struggling to discover a quick and easy shortcut for this task. My attempts with Ctrl + Click only led me to the initial occurrence of the variable's decla ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...