0

I'm new to VUE i have issue to convert dict to JSON in my Vue data

i have a paragraph with innerHTML {'id': '1', 'name':'test'}

i need to convert this string to object in my Vue.

I try:

const helloWorld = new Vue({

   el:'#helloVue',


   data: {
      dict:JSON.parse(JSON.stringify(document.getElementById('vuedata').innerHTML)),


   },


 delimiters: ['[[', ']]'],

})

but when i expect Vue data it show me a string, not an object.

str
  • 42,689
  • 17
  • 109
  • 127
dmitriy_one
  • 477
  • 1
  • 5
  • 16
  • 1
    Duplicate of [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes) – str Dec 02 '19 at 18:58
  • The call to `JSON.stringify` is redundant as `innerHTML` returns a string and to have `JSON.parse` work properly you need to replace the single-quotes with double-quotes (for example using `str.replace(/'/g, '"')`). – Andre Nuechter Dec 02 '19 at 19:08
  • Javascript doesn't have dict's, it has object's and Map's, please use to learn the proper terminology for the language so that you don't confuse others, thanks, I could edit the question for you I suppose, but if you haven't edited a question before, here's your chance! – Dexygen Dec 02 '19 at 19:12

1 Answers1

0

You can compute that dict value directly in data but it's better to do it in computed, like so:

computed: {
  dict() {
    return JSON.parse(JSON.stringify(document.getElementById('vuedata').innerHTML))
  }
}

You can then use that value in template, like you would normally use data properties:

<div>{{dict}}</div>

Or use it in other computed / methods by specifying this., example:

console.log(this.dict)

By the way, the data property should return the values, like this:

data() {
  return {
    dict1: ...,
    dict2: ...,
    ...
  }
}
AlekseyHoffman
  • 2,438
  • 1
  • 8
  • 31