如何在JavaScript中创建和空的JSON并动态添加键和其他JSON对象?

发布于 2025-02-14 01:06:14 字数 542 浏览 1 评论 0原文

如何在JavaScript中创建和空的JSON并动态添加键和其他JSON对象?

mydata = {}

newdata = {
       'first': [ {'1': 'test'} ]
}

尝试了这个

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const myJSON = '{}';
myJSON['first']['1'] = 'test';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

How to create and empty JSON in JavaScript and add keys and additional JSON objects dynamically?

mydata = {}

to

newdata = {
       'first': [ {'1': 'test'} ]
}

I tried this

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const myJSON = '{}';
myJSON['first']['1'] = 'test';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清音悠歌 2025-02-21 01:06:14

将json解析到一个物体中,然后设置他的属性

const myJSON = '{}';
const myObj = JSON.parse(myJSON);
myObj['first'] = [{'1':'test'}];

console.log(myObj);
newdata = {
       'first': [ {'1': 'test'} ]
}

Parse the json into an object, then set his properties

const myJSON = '{}';
const myObj = JSON.parse(myJSON);
myObj['first'] = [{'1':'test'}];

console.log(myObj);
newdata = {
       'first': [ {'1': 'test'} ]
}

尐偏执 2025-02-21 01:06:14

尝试一下

var newData = { first: [{ 1: "test" }] };

//or 

const myJson = {};
myJson["first"]= [];
var newItem={ "1": "test" };
myJson["first"].push(newItem);
myJson["second"]= [];
newItem={ "2": "test" };
myJson["second"].push(newItem);

console.log(JSON.stringify(myJson));

try this

var newData = { first: [{ 1: "test" }] };

//or 

const myJson = {};
myJson["first"]= [];
var newItem={ "1": "test" };
myJson["first"].push(newItem);
myJson["second"]= [];
newItem={ "2": "test" };
myJson["second"].push(newItem);

console.log(JSON.stringify(myJson));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文