Fly higher! Sky is the limit!

webの現場で働く人のブログ

JSONジェネレータを作る(Vue.jsとかJavaScriptとか)

!!!いきなり完成品!!!!

See the Pen JSON GENERATOR by paradox_tm (@takumaro-web) on CodePen.

作成手順

1. JSONを用意して、HTML上に表示する。

{
    "name": "安室奈美恵",
    "sex": "女性",
    "age": "41"
}

私が今回利用したサイトはこちら(というかいつも利用している。)
http://hilite.me/

2. 値が変わるところを書き換えていく。

JSONジェネレータを作る(Vue.jsとかJavaScriptとか)

※ 大枠のmain要素に#generatorも追加してます。

JS - code

var createJson = new Vue({
  el: '#generator',
  data: {
    name: "安室奈美恵",
    sex: "女性",
    age: "41"
  }  
});

3. それぞれの値を変更できるようにinputタグを用意する。

これでリアルタイムにJSONの値を変更することができる。

JSONジェネレータを作る(Vue.jsとかJavaScriptとか)

エアロスミスは、バンドやし!バンド結成から48年やし(2018年現在)!

JSONをダウンロードするためのJSを記述

var test;
function json_create() {
  test = [
      {
          "name": "安室奈美恵",
          "sex": "女性",
          "age": "41"
      }
  ];
}

function json() {
  var data = JSON.stringify(test);
  var a = document.createElement('a');
  a.textContent = 'Download JSON' //ボタンの文言を定義
  a.download = 'test.json'; //JSONの名前を定義
  a.href = window.URL.createObjectURL(new Blob([data], { type: 'text/plain' }));
  a.dataset.downloadurl = ['text/plain', a.download, a.href].join(':');
  var exportLink = document.getElementById('download');
  exportLink.appendChild(a);
}json();

参考サイト https://kuroeveryday.blogspot.com/2015/07/javascriptExportFile.html

値をリアルタイムで監視し、生成するJSONの中身も書き換えていく

ここが今回のミソ。

function jsonGenerat() {
  test = [
      {
          'name': createJson.$data.name,
          'sex': createJson.$data.sex,
          'age': createJson.$data.age
      }
  ];
}

createJson.$watch('name', function (newValue, oldValue) {
   document.querySelector('#download a').remove();
   jsonGenerat();
   json();
})
createJson.$watch('sex', function (newValue, oldValue) {
   document.querySelector('#download a').remove();
   jsonGenerat();
   json();
})
createJson.$watch('age', function (newValue, oldValue) {
   document.querySelector('#download a').remove();
   jsonGenerat();
   json();
})
  • 生成するJSONの中身もinputタグで書き換えられた内容にする
  • ダウンロードリンクも新しいものになるように毎回上書きをおこなう

これでJSONジェネレータの完成!!!

あまり難しいテクニックもなく、このようなジェネレータを作ることができました。
あなたの日々の更新が少し楽になるかもしれません。

以上です。