Search code examples
javascriptcssjsonxpathjsonpath

Highlight selected text from JSONPath using CSS


I am using JSONPath to select some elements from a JSON file. I want the selected elements to be displayed on an html page. (The entire JSON should be displayed with only the selected tags highlighted)

The final result should look like the XPath Evaluator in the Defient.js site.

So far, I've managed to use the JSONPath to select the element I want and get it as the output. Also, I can use JSON.stringify in a <pre> tag to print the JSON to the webpage.

What I want to know is how I should go about highlighting the selected text. The output can't be simply used to generate a regex because it might match fields that are not selected by the JSONPath filter.


Solution

  • As you've told that you can get the path, it'll be just matter of wrapping the value for the corresponding path with a html tag and give a class. Then you can highlight with css.

    pre {
       background-color: ghostwhite;
       border: 1px solid silver;
       padding: 10px 20px;
       margin: 20px; 
       }
    .json-key {
       color: brown;
       }
    .json-value {
       color: navy;
       }
    .json-string {
       color: olive;
       }
        <pre><code id="planets">[
           {
              <span class="json-key">name</span>: <span class="json-string">"Earth"</span>,
              <span class="json-key">order</span>: <span class="json-value">3</span>,
              <span class="json-key">stats</span>: {
                 <span class="json-key">life</span>: <span class="json-value">true</span>,
                 <span class="json-key">mass</span>: <span class="json-value">5.973600000000001e+24</span>
              }
           },
           {
              <span class="json-key">name</span>: <span class="json-string">"Saturn"</span>,
              <span class="json-key">order</span>: <span class="json-value">6</span>,
              <span class="json-key">stats</span>: {
                 <span class="json-key">life</span>: <span class="json-value">null</span>,
                 <span class="json-key">mass</span>: <span class="json-value">5.6846e+26</span>
              }
           }
        ]</code></pre>

    Example replacer - but not necessarily.