Is there a way to use regex to selectively color JSON keys?

My goal in JavaScript is to extract all of the JSON keys using regular expressions. I am assuming that the JSON data will be formatted with each key-value pair on a new line, like this:

{
    "name": "Jane",
    "age": 30,
}

In simple terms, I am looking to capture the first occurrence of any string enclosed in double quotes.

Answer №1

Using regular expressions may not be the best approach in this situation. Instead, I would recommend constructing an output string based on your JSON data:

let jsonData = {
  name: "John Doe",
  age: 30,
  status: "active",
};

let formattedDataString = Object.entries(jsonData)
  .reduce((acc, [key, value]) => `${acc}
    <span class='json-key'>"${key}": </span>
    <span class='value'>"${value}"</span>,<br/>`,
    `{<br/>`) + `}`;

document.write(formattedDataString);
.json-key {
  color: blue;
  margin-left: 8px;
  font-family: monospace;
}

.value {
  font-family: monospace;
}

Answer №2

Let's break it down step by step:

(?<=")    (.*?)    (?=":)
   1        2         3
  1. Using lookbehind to ensure a quote precedes the desired text.
  2. Capturing the actual text you want.
  3. Applying lookahead to make sure a quote and colon come after the text.

Once identified, replace it with:

<span style="color: red;">$1</span>

Check out this demonstration

Answer №3

I have implemented recursion to achieve this.

JSON data

let json = {
  name: "John",
  age: 30,
  details: {
    city: "New York",
    country: "USA"
  },
};

The following function will loop through the JSON object, encapsulate its keys and values within span tags, and separate them using JSON syntax tokens.

let json = {
  name: "John",
  age: 30,
  location: "Earth",
  details: {
    city: "Los Angeles",
    state: "California"
  }
};

let styledJson = "<span class='syntax'>{</span><br/>" + formatJSON(json,24) + "<br/><span class='syntax'>}</span>";

document.write(styledJson);

function formatJSON(data, margin) {

  var formattedData = '';

  Object.entries(data).forEach(([key, value]) => {
    formattedData += `<span style='margin-left:${margin}px;' class='json-key'>"${key}"</span><span class="syntax" ${this.scope}>:</span>`
    if (typeof value == "object") {
      formattedData += `<span class='syntax'>{</span><br/>`
      formattedData += this.formatJSON(value, margin + 12)
      formattedData += `<br/><span style='margin-left:${margin}px;' class='syntax'>}</span>`
    } else {
      if (Object.keys(data).reverse()[0] != key) formattedData += `<span class='value'>"${value}"</span><span class="syntax">,</span><br/>`
      else
        formattedData += `<span class='value'>"${value}"</span>`
    }
  })
  
  return formattedData;
}
.json-key {
  color: #7A01FF;
  margin-left: 10px;
  font-family: Consolas;
}

.value {
  color: #F9D372;
  font-family: Consolas;
}

.syntax {
  color: #EEEEEE;
  font-family: Consolas;
}

body {
  background-color: #232932;
  padding: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.5.4/typescript.min.js"></script>

Thank you

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 term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

Is it possible to send a server response without requiring a callback function to be provided from the client side?

Clarifying the Issue When utilizing .emit() or .send() with a desire to confirm message reception (referred to as acknowledgements), the syntax typically involves: socket.emit('someEvent', payload, callback); The focus of this discussion is on ...

The Ajax request is not successfully communicating with the PHP script

I am struggling with an issue regarding ajax calling a PHP code without changing the current page. Despite checking the php_error.log, I cannot find any reference to the PHP file. There are no errors displayed on screen, leaving me clueless about how to re ...

The Strapi admin panel seems to be stuck on an eternal loading loop when accessed locally on my localhost

section, some unexpected issues arose recently. This sudden occurrence took place following some modifications that involved adding a significant number of new Fields attributes to a specific Collection Type. As a result, my Strapi CMS NodeJS backend is n ...

Encountering a JSON code issue while attempting to dump/load a dictionary, resulting in an 'Extra Data' error

I'm working on loading a dictionary onto a JSON file, and then later in the code searching the JSON dictionary for a key to load and printing the associated values. However, I keep encountering an error. Here's how I am storing the data into the ...

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

"Twice the loading of Meteor templates: once with an undefined collection, and once with it

After searching various resources for solutions to my issue, I stumbled upon this helpful and . Both of these links provided valuable insights. The issue I'm facing is that one of my templates is loading twice - first with the collection undefined, ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...

Can a function be embedded within a React render method that includes a conditional statement to update the state using setState()?

My application randomly selects three values from an array found within defaultProps and then displays these values inside div elements in the return JSX. It also assigns these values to properties in the state object. I am facing a challenge where I need ...

Show the input from one HTML form on a different HTML form

Seeking guidance on utilizing local storage in HTML5. How can I extract information from one form and present it on another HTML form page? Picture this: two forms at play here. Upon populating form 1 and hitting the submit button, the content should be v ...

Identifying a change in the source location of an iframe element

I am working with an iframe object that is currently set to a specific page's URL. Here is an example: <iframe src="http://en.wikipedia.org/wiki/Special:Random"></iframe> My goal is to display an alert whenever the location of the iframe ...

Mastering jQuery UI: A beginner's guide to utilizing the date picker widget

This is my first venture into the world of HTML and JavaScript, so I am asking for your patience. I am trying to incorporate the Datepicker widget from jQuery UI, following the instructions on the Getting Started page. There seems to be an issue with lin ...

Enhancing an array item with Vuex

Is there a way to change an object within an array using Vuex? I attempted the following approach, but it was unsuccessful: const state = { categories: [] }; // mutations: [mutationType.UPDATE_CATEGORY] (state, id, category) { const record = state. ...

Creating a multi-level mobile navigation menu in WordPress can greatly enhance user experience and make

Hey there, I am currently in the process of developing a custom WordPress theme and working on creating a mobile navigation system. Although I have managed to come up with a solution that I am quite pleased with after multiple attempts, I have encountered ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...