Vue

by WILLIAM CORREA

HTML

<div id="app">
  <textarea v-model="json"></textarea>
  <textarea v-model="form"></textarea>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Vue

const serialize = (object, prefix = '') => {
  const string = []
  for (let property in object) {
    if (!object.hasOwnProperty(property)) {
      continue
    }
    let key = prefix ? `${prefix}[${property}]` : property
    let value = object[property]
    if (value === undefined) {
      continue
    }
    let serialized = `${key}=${value}`
    if (typeof value === 'object') {
      serialized = serialize(value, key)
    }
    string.push(serialized)
  }
  return string.join('&')
}

const unSerialize = (url, prefix = '') => {
  const object = {}
  const regex = /(^|&)([^=]+)=([^&]+)/g
  let matches
  let key
  let value

  while ((matches = regex.exec(url)) !== null) {
    if (matches.index === regex.lastIndex) {
      regex.lastIndex++
    }
    matches.forEach((match, groupIndex) => {
      if (groupIndex === 0 || groupIndex === 1) {
        return
      }
      if (groupIndex === 2) {
        key = !prefix ? match : match.substring(prefix.length + 1, match.length - 1)
        return
      }
      value = match
    })
    if (!key || !value) {
      continue
    }
    object[key] = value
  }
  return object
}

new Vue({
  el: "#app",
  data: {
    json: '',
    form: ''
  },
  methods: {
  	toForm: function(){
    	this.form = serialize(JSON.parse(this.json))
    },
  	toJSON: function(){
    	this.json = unserialize(this.form)
    }
  },
  watch: {
  	form: function () {
    	this.toJSON()
    },
  	json: function () {
    	this.toForm()
    }
  }
})