简体   繁体   中英

How to color only JSON keys via regex?

In javascript, I want to capture all of my json keys via regex. Let's assume that the json outputs with every key-value pair in a new line. Eg

{
    "foo": "bar",
    "age": 23,
}

In other words, every first instance of a string with double quotes.

I don't think regular expressions will cut it here, I would suggest you build an output string based off of your JSON:

 let json = { foo: "bar", age: 23, test1: 1, test2: 2, test3: 3, }; let formattedJSONString = Object.entries(json) .reduce((acc, [key, value]) => `${acc} <span class='json-key'>"${key}": </span> <span class='value'>"${value}"</span>,<br/>`, `{<br/>`) + `}`; document.write(formattedJSONString); 
 .json-key { color: blue; margin-left: 8px; font-family: monospace; } .value { font-family: monospace; } 

Here's how you'd work it:

(?<=")    (.*?)    (?=":)
   1        2         3
  1. Lookbehind to require a quote before the text you want.
  2. What you actually want to capture.
  3. Lookahead to require a quote and colon be present after your text.

Then, replace it with:

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

Here is a demo

I've used recursion for this.

JSON object

let json = {
  foo: "bar",
  age: 23,
  foo2: {
    hello: "world",
    world: "hello"
  },
};

This function will iterate over the JSON object and add its keys and values into span tags and seprate them with JSON syntax tokens

 let json = { foo: "bar", age: 23, hi: "bye", bar: { hi: "now", now: "hi" } }; let stylizedJson = "<span class='syntax'>{</span><br/>" + createFormattedJSON(json,24) + "<br/><span class='syntax'>}</span>"; document.write(stylizedJson); function createFormattedJSON(data, margin) { var formattedJson = ''; Object.entries(data).forEach(([key, value]) => { formattedJson += `<span style='margin-left:${margin}px;' class='json-key'>"${key}"</span><span class="syntax" ${this.scope}>:</span>` if (typeof value == "object") { formattedJson += `<span class='syntax'>{</span><br/>` formattedJson += this.createFormattedJSON(value, margin + 12) formattedJson += `<br/><span style='margin-left:${margin}px;' class='syntax'>}</span>` } else { if (Object.keys(data).reverse()[0] != key) formattedJson += `<span class='value'>"${value}"</span><span class="syntax">,</span><br/>` else formattedJson += `<span class='value'>"${value}"</span>` } }) return formattedJson; }
 .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>

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM