"Enhance the appearance of JSON strings in a Vue.js 2 project using

In an attempt to format my JSON string into a highlighted syntax or something similar to JSON prettify using pre element tags. I'm not looking for a tree JSON viewer, just a clean and nice JSON syntax highlight.

Template

<div id="app">
  <pre>{{{ json | jsonPretty }}}</pre>
</div>

Vue

var vm = new Vue({
  el: '#app',
  data() {
    return {
      json:'{ "name: "John Doe" }'
    }
  },
  filters: {
    jsonPretty: function(value) {
      let json = JSON.stringify(JSON.parse(value), null, 2)
      json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
      return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+]?\d+)?)/g, function(match) {
        var cls = 'number'
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = 'key'
          } else {
            cls = 'string'
          }
        } else if (/true|false/.test(match)) {
          cls = 'boolean'
        } else if (/null/.test(match)) {
          cls = 'null'
        }
        return '<span class="' + cls + '">' + match + '</span>'
      })
    }
  }
});

CSS

pre {
  outline: 1px solid #ccc;
  padding: 15px; 
  margin: 5px;
  background: white;
 }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

I tested it on JSFiddle and it worked fine but encountered errors when testing with the official VueJS template in Webpack.

ERROR in ./~/vue-loader/lib/template-compiler?{"id":"data-v-4b8ecaca","hasScoped":true,"transformToRequire":{"video":"src","source":"src","img":"src","image":"xlink:href"}}!./~/vue-loader/lib/selector.js?type=template&index=0!./src/components/Hello.vue
(Emitted value instead of an instance of Error) 
  Error compiling template:

  <div class="hello">
    <div class="">

      <pre>{{{ json | jsonPretty }}}</pre>
    </div>
  </div>

  - invalid expression: {{{ json | jsonPretty }}}

 @ ./src/components/Hello.vue 10:2-300
 @ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
 @ ./src/App.vue
 @ ./src/main.js
 @ multi ./build/dev-client ./src/main.js

Edit: added JSFiddle link

https://jsfiddle.net/Ljck1wmL/5/

Answer №1

I seem to be struggling to locate any information regarding that {{{ html }}} syntax. The official documentation suggests using the v-html directive instead.

It's worth noting that Vue 2.x filters are restricted to moustache and v-bind expressions. As stated in this issue on GitHub, filters cannot be used within v-html.

In other cases, it is recommended to utilize a computed property or method.

<pre v-html="prettyAreaData"></pre>

Additionally,

computed: {
  prettyAreaData: function() {
    var value = this.areaData;
    // continue with your function logic here

I have made adjustments to your JSFiddle to incorporate Vue 2.x, assuming you are using it locally. I also modified the data function to a plain object as suggested.

https://jsfiddle.net/Ljck1wmL/7/

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

Utilizing Ng-Required for Angular Form Validation

FIDDLE HERE: http://jsfiddle.net/TegFf/48/ Within my form, there are radio buttons (you can view them in the Fiddle link above) that need to validate the following scenarios: The user must select a radio button with a corresponding dollar amount If "cus ...

Websites using UTF-8 encoding facing challenges with specific browsers

I recently created a web application using JSP for the presentation layer. In each JSP file, I included charset definitions like this: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> ... How ...

What is the best way to have a single item in a list displayed in two columns?

Can the angular repeat achieve this functionality? I am looking to loop the two elements together. Any assistance would be greatly appreciated! Controller: $scope.date=[ {ID:1,Date:'2016-11-12'}, {ID:2,Date:'2016-11-15'}, ...

Changing the way users are linked in a post using HTML tags (VUE-NODE)

I am trying to modify a body property that includes usernames @username1 and @username2. Is it feasible to use regex to transform these nicknames into router links? The desired output should be like this (with the @ removed in the link profile) <router ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Is it possible to implement validation for the 4th digit of a number before submitting the page by using a combination of ajax and JavaScript

Currently, I am working on a scenario where a postal code needs to be saved and it is a mandatory requirement. I have implemented an AJAX call triggered by the keyup event after entering 4 digits in the postal code field. The AJAX functionality works corre ...

Converting decimal formatting in Mule ESB using an expression node

Previously, I had a result from a database connection SQL statement that looked like this: [{"BALANCE":111.11},{"BALANCE":222.12},{"BALANCE":444.30}] To calculate the sum, I used the following expression node content: sum = 0; foreach (row : message.pay ...

How to retrieve values from a nested array in a Next.js application

I am diving into the world of nextjs and apollo for the first time, and I am currently facing a challenge with using .map to loop through database results. Below is the code for my component: import { gql, useQuery } from "@apollo/client" import ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

Using Webpack to directly embed image paths in your code

I am working on a project that uses webpack and vue.js. I encountered an issue when trying to add an image to the vue template using src '/images/imageName.png', which resulted in a 404 error. How can I adjust the configuration to recognize absol ...

The occurrence of fsevents results in the failure of module parsing due to encountering an unexpected character "'&#

When using next.js, I encounter the following error: Failed to compile. ./node_modules/fsevents/fsevents.node 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to handle this file type, currently no loader ...

Locate the selected radio button's label

There are 25 radio button groups on my page. Each group has a specific action that needs to be performed when a radio button is selected. In order to execute the correct action for each group, I require the NAME attribute of that particular radio group. ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Hyperlinks springing to life on mouseover

After spending countless hours tweaking my CSS code, I've hit a roadblock and need some assistance. My issue lies with the links on hover that seem to be jumping unexpectedly. The goal was to create a mobile-responsive hamburger menu that transforms i ...

Using AngularJS, passing a value from outside a directive to the directive and detecting changes in the

As a newcomer to AngularJs, I am facing a challenge in retrieving data from outside a directive. The scenario involves multiple input fields being updated and the necessity for the directive to process this information. For instance, consider the code sni ...

Check if the DIV element does not exist in the DOM before using the

I have been working on a large project and what I need is if div 1 does not contain div 2 as a child{ div1.appendChild(div2) } However, I am facing difficulties in solving this issue Here is my code snippet <script> dc = document.createElement( ...

Exploring the concept of nested dictionaries in web development: how to utilize

Here is a snippet of my JavaScript code: var emotions = {}; $('#emotions').children('#emotionFields').each(function(){ emotions[$(this).find($('.emotion')).val()]=$(this).find($('.value')).val() }); $ ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Fade in and out animation for flash notifications

Is there a way to create a flash message with a smooth fade in and out animation using jQuery? I would appreciate any recommendations on the most efficient approach for achieving this effect. ...