初めに
今回はユーザーがテキストボックスに入力した内容を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に変換するというプログラムを書きました。
それではまたお会いしましょう!
Comments
この処理は
getElementById()ではなくquerySelectorAll()を使ってある程度まとめて取得してしまえば、その後のループ処理を少し単純化できると思います。スクリプト全体を簡略化してみました。
Let's comment your feelings that are more than good