LoginSignup

Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

初めに

今回はユーザーがテキストボックスに入力した内容をJsonに変換するプログラムを書いてみました。

ファイル構成

今回はhtmlファイル一つで行きます。

コピペ

以下のコードをコピペします:

main.html
<!DOCTYPE html>
<html>
<head>
    <title>文字列をJsonに変換するプログラム(?)</title>
    <style>
        body {
            min-height: 100%;
            display: flex;
            flex-direction: column;
            text-align: center;
        }
        button {
            height: 30px;
            background-color: black;
            color: white;
            border: none;
            margin-top: 10px;
        }
        input[type="text"] {
            height: 30px;
            border: 1px solid black;
            margin-top: 10px;
        } 
        footer {
            width: 100%;
            height: 100px;
            background-color: rgb(97, 97, 97);
            color: white;
            font-weight: 1;
            flex-direction: column;
        }
        button:hover {

            background-color: rgb(90, 90, 90);

        }
        header {
            width: 100%;
            height: 100px;
            background-color: rgb(97, 97, 97);
            color: white;
            font-weight: 1;
            flex-direction: column;
        }
    </style>
</head>
<body>
    <header>
        <h1 style="font-weight: 1;">文字列をJSONに変換するプログラム</h1>
    </header>
    <main>
        <p>ここに文字列を入力</p>
        <div id="properties">
            <div id="property0">
                プロパティ名:<input type="text" id="name0">設定:<input type="text" id="value0">
            </div>
        </div>
        <button onclick="removeUnder()">一番下のプロパティを削除</button>
        <br><button onclick="addTop()">一番下にプロパティを追加</button>
        <br><button onclick="convertToJson()">JSONに変換</button>
        <div id="jsonResult"></div>
    </main>
    <footer>
        <p>©2024 </p>
    </footer>
    <script>
        let propertyCount = 1;

        function addTop() {
            let newDiv = document.createElement('div');
            newDiv.id = 'property' + propertyCount;
            newDiv.innerHTML = `プロパティ名:<input type="text" id="name${propertyCount}">設定:<input type="text" id="value${propertyCount}">`;
            document.getElementById('properties').appendChild(newDiv);
            propertyCount++;
        }

        function removeUnder() {
            if (propertyCount > 1) {
                propertyCount--;
                let elem = document.getElementById('property' + propertyCount);
                elem.parentNode.removeChild(elem);
            }
        }

        function convertToJson() {
            let jsonObject = {};
            for (let i = 0; i < propertyCount; i++) {
                let name = document.getElementById('name' + i).value;
                let value = document.getElementById('value' + i).value;
                if (name.trim() !== '') {
                    jsonObject[name] = value;
                }
            }
            let jsonResult = JSON.stringify(jsonObject);
            document.getElementById('jsonResult').innerText = jsonResult;
        }
    </script>
</body>
</html>

※修正をGPTにやってもらいました。

仕組み

1,ユーザーがプロパティ名とその設定をテキストボックスに入力します
2,Jsonに変換を押すとconvertJson()が実行されます
3,convertJsonで、ユーザーが入力したすべての情報をjsonObjectに格納して、stringfyでjsonに変換しています。

最後に

みなさん、いかがだったでしょうか、今回はユーザーが入力したものをJsonに変換するというプログラムを書きました。
それではまたお会いしましょう!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
qqn5192

@qqn5192

プログラミング初心者です。間違えることが多いので、間違えているところがあればコメントで教えてくれると嬉しいです。よろしくお願いします!

Comments

x9200910
@x9200910
function convertToJson() {
   let jsonObject = {};
   for (let i = 0; i < propertyCount; i++) {
       let name = document.getElementById('name' + i).value;
       let value = document.getElementById('value' + i).value;
       if (name.trim() !== '') {
           jsonObject[name] = value;
       }
   }
   let jsonResult = JSON.stringify(jsonObject);
   document.getElementById('jsonResult').innerText = jsonResult;
}

この処理はgetElementById()ではなくquerySelectorAll()を使ってある程度まとめて取得してしまえば、その後のループ処理を少し単純化できると思います。

function convertToJson() {
  const names  = [...document.querySelectorAll('[id*=name]')] .map(v => v.value.trim());
  const values = [...document.querySelectorAll('[id*=value]')].map(v => v.value.trim());

  const jsonObject = {};
  names.forEach((v, i) => v && (jsonObject[v] = values[i]));
  document.getElementById('jsonResult').textContent = JSON.stringify(jsonObject);
}
0
x9200910
@x9200910

スクリプト全体を簡略化してみました。

function addTop() {
  properties.insertAdjacentHTML('beforeend',
    '<div>プロパティ名:<input type="text">設定:<input type="text"></div>');
}

function removeUnder() {
  properties.children.length > 1 && [...properties.children].at(-1).remove();
}

function convertToJson() {
  const names  = [...document.querySelectorAll('input:nth-child(odd)')] .map(v => v.value.trim());
  const values = [...document.querySelectorAll('input:nth-child(even)')].map(v => v.value.trim());
  const jsonObject = {};
  names.forEach((v, i) => v && (jsonObject[v] = values[i]));
  document.getElementById('jsonResult').textContent = JSON.stringify(jsonObject);
}
0

Let's comment your feelings that are more than good

Being held Article posting campaign

これからの情報伝達手段の在り方について考えてみよう!

~
View details

markdown AIを使った記事を投稿しよう!

~
View details
0
0

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address