How to convert an array to JSON string in VueJS?

Hi Friends đź‘‹,

Welcome To SortoutCode! ❤️

To convert an array to JSON string in VueJS. There are several methods to convert an array to JSON string, we are going to use JSON.stringify(Object.assign({},arry)) methods. In these methods arry stand for your array data.

Short solution

parentComp.vue

var arry = ["magzine", "sortout", "google", "youtube"]; // Array

var ObjA = JSON.stringify(Object.assign({},arry));

console.log(ObjA); // string : {"0":"magzine","1":"sortout","2":"google","3":"youtube"}

Today, I am going to show you How you convert the array into JSON string in VueJS?

Table of Content

  • Setup the Vue (Optional)
  • Create FirstComponent.vue and import it into App.js
  • Convert an array to json string

This article will guide you to How do I change an array to JSON string in vueJS

Setup the Vue.js

First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.

How to Install the VueJS project?

Create FirstComponent.vue and import it into App.js

Create the new component in the src/components/ components folder. The component name is FirstComponent.vue and imported into the App.js file:

App.js

<template>
  <FirstComp />
</template>

<script>
import FirstComp from "./components/FirstComp.vue";
export default {
  name: "App",
  components: {
    FirstComp: FirstComp,
  },
};
</script>

Convert an array into JSON string using JSON.stringify()

To convert an array to JSON string in vuejs. We are going to define the array arry in the data property. And we are going to convert this array into a JSON string using the JSON.stringify(Object.assign({},arry)).

Let’s take a short example to better understand.

FirstComp.vue

<template>
  <div class="hello">
    <h1>Welcome to Sortoucode</h1>
    <p>Array : {{ ary }}</p>
    <p v-if="output">string : {{ output }}</p>
    <p v-if="output">DataType is : {{ typeof output }}</p>
    <button @click="convertData">Convert</button>
  </div>
</template>

<script>
export default {
  name: "FirstComp",
  data() {
    return {
      ary: ["magzine", "sortout", "google", "youtube"],
      output: "",
    };
  },
  methods: {
    convertData() {
      this.output = JSON.stringify(Object.assign({}, this.ary));
    },
  },
};
</script>

For now, let’s check the output.

Output

con an array to JSON string object

Links

Here, is the above program code sandbox link of how to convert an array to JSON string in vue js. Then you can use it whenever you went and do the changes as per your requirements.

Codesandbox

All the best đź‘Ť.

Follow me on Twitter