Home > Enterprise >  convert string to Object in vue using Json.parse
convert string to Object in vue using Json.parse

Time:09-16

I want to transform the the input value from the input element into an Object

using Json.parse() to convert the internData value does not convert the string to an Object

doing the same operation in the browser console returns the correct outcome.

let data = "[1,2,3,4]";

JSON.parse(datas)
(4) [1, 2, 3, 4]

typeof z
'object'

What am I missing here ?

new Vue({
  el: "#app",
  data() {
    return {
      datatype: "foo",
      internData: "[1, 2, 3]",
    };
  },

  methods: {
    transformData() {
      //
      //
      JSON.parse(this.internData);

     
      //  this.internData.push(12);

      return this.internData;
    },
    whatFormat(){
      console.log(typeof this.internData)
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<html>
  <body>
    <div id="app">
      <h5> {{ data }}</h5>
     
       <input v-model="internData" @input="onInputme" />
      
       <button type="button" @click="transformData">click to transform</button>
   <button type="button" @click="whatFormat">what data type</button>
    
   
    
    </div>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
   
  </body>
</html>

CodePudding user response:

The issue that you currently have is that you are not updating the internData from the transformData function youe should reassign internData with JSON parsed format of same inside the function just like below

transformData() {
  this.internData = JSON.parse(this.internData);
}

OR

You could make transformData as a computed property and watch for the type of transformData. Here you can get rid of the click event to parse the data.

new Vue({
  el: "#app",
  data() {
    return {
      datatype: "foo",
      internData: "[1, 2, 3]",
    };
  },
  methods: {
    whatFormat() {
      console.log(this.transformData);
      console.log(typeof this.transformData);
    }
  },
  computed: {
    transformData: function () {
      return JSON.parse(this.internData)
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input v-model="internData" />
  <button type="button" @click="whatFormat">what data type</button>
</div>

CodePudding user response:

Your transformData function transforms the string, but the newly created object is not assigned to the internData property.

This should do the trick:

transformData() {
  this.internData = JSON.parse(this.internData);
},
  • Related