javascript - 使用一个输入从 HTML 页面创建 JSON 文件
问题描述
现在我正在尝试输入类型=“文本”
<label for="psw"><b>name</b></label>
<input type="text" placeholder="Insert ValueXml value" name="psw" required>
生成具有默认值的 JSON 文件,其中输入仅更改此值(“ValueXml”:“Accounting Header 1”)。这应该是应该出来的 JSON(很多值都有前缀,所以我不必全部更改)
{
"fileType": {
"accountingType": {
"docGroup": 100,
"docApp": 100,
"decimals": 2
}
},
"data": {
"format": "documentchange",
"error": "",
"data": [
{
"document": {
"fileVersion": "1.0.0",
"creator": {
"name": "FinancialPlaWriter",
"version": "1.0.0"
},
"dataUnits": [
{
"nameXml": "FileInfo",
"data": {
"rowLists": [
{
"rows": [
{
"fields": {
"SectionXml": "Base",
"IdXml": "HeaderLeft",
"ValueXml": "Accounting Header 1"
},
"operation": {
"name": "modify"
}
},
{
"fields": {
"SectionXml": "AccountingDataBase",
"IdXml": "OpeningDate",
"ValueXml": "20210101"
},
"operation": {
"name": "modify"
}
},
{
"fields": {
"SectionXml": "AccountingDataBase",
"IdXml": "ClosureDate",
"ValueXml": "20231231"
},
"operation": {
"name": "modify"
}
}
]
}
]
}
}
]
}
}
]
}
}
例如“ValueXml”:“Accounting Header 1”,他希望用户通过 HTML 输入输入他想要的名称,例如:“ValueXml”:“MAMMA_MIA”,例如:
所以我不知道如何创建这样一个 JSON 文件而不让我大吃一惊你有没有机会知道一种方法?
解决方案
如果我理解正确,您想生成一个已经具有默认值的 json 文件,并且您只想更改一个字段,对吗?英语也不是我的语言:)
试试这个代码:
//this function get the value of input and changes "ValueXml" if it has a value;
function makeJson(){
let inputValue = document.getElementById('inputId').value;
//put your json here
return {
"data": {
"ValueXml": inputValue ?? "Accounting Header 1"
}
}
}
//Generate jsobject as json file
//Credits: https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
//now call functions
function download(){ downloadObjectAsJson(makeJson(), 'myjsonfile'); }
<input id="inputId" value="Change me!" />
<button onclick="download">download json</button>
推荐阅读
- laravel - 即使我已经将其移除,仍然可以检测到 livewire 组件和刀片
- javascript - ReferenceError:从window.open()刷新应用程序后未定义cordova
- android - LiveData 数据更改后 UI 不会更新
- python - 无法在 MacOS 上使用 pip
- java - 将 ImageButtons 附加到 OnClickListener 的位图
- ios - 在 SwiftUI 中折叠顶部栏
- r - 使用 rselenium r 在网站中滚动内部滚动条
- rust - 如何在 Rust 中打印 sha256 哈希?(通用数组)
- flutter - 颤振2.0未处理的异常:空值检查运算符用于空值
- python - 在 Pyinstaller App 的子目录中包含并启动 py 文件