简体   繁体   English

在 json 中插入 javascript 变量值

[英]inserting javascript variable value in json

i have a JSON variable which looks like this:我有一个 JSON 变量,如下所示:

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]};

i have two vaiables我有两个变量

x=2; y=jam;

i want to push the variables in json such that x is event_id and y is event_name, so that my json will look like-我想推送 json 中的变量,使 x 是 event_id,y 是 event_name,这样我的 json 看起来像-

{"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"},
{"event_id": "2", "event_name": "jam"}
]};

the function iam using to push is用于推送的 function 是

k='({"event_id":"'+x+'","event_name":"'+y+'"})';
san.events.push(k);

where san is the variable in which i stored the json. iam parsing the variable san and applying the push action and stringifying it and displaying it, but in the result my json data syntax is changing like additional '/' symbols are generating in the json.其中 san 是我存储 json 的变量。我正在解析变量 san 并应用推送操作并将其字符串化并显示它,但结果我的 json 数据语法正在发生变化,就像在 json 中生成额外的“/”符号一样.

JSON objects are first class citizens in JavaScript, you can use them as literals. JSON对象是JavaScript中的一等公民,您可以将它们用作文字。

var k= {"event_id": x, "event_name":y};
san.events.push(k);

As the above is the exact same thing as: 如上所述完全相同:

var k = new Object();
k.event_d = x;
k.event_name = y;
san.events.push(k);

JSON is just a way to represent regular objects in JavaScript. JSON只是一种在JavaScript中表示常规对象的方法。

If you really want to transform strings into JSON, you can use the JSON.parse() method, but you normally want to avoid this. 如果您真的想将字符串转换为JSON,可以使用JSON.parse()方法,但通常要避免这种情况。

EDIT 编辑

As @Alvaro pointed out, even though you can create regular Objects using the JSON syntax, it's not synonym of Object, it' just a way of representing the Object data, and not just any data, JSON cannot represent recursive objects. 正如@Alvaro所指出的,即使你可以使用JSON语法创建常规对象,它也不是Object的同义词,它只是表示Object数据的一种方式,而不仅仅是任何数据,JSON不能代表递归对象。

The variable value is missing Quote here 变量值缺少引用这里

x=2; y='jam';

and change push code like this 并改变这样的推送代码

k={"event_id":"'+x+'","event_name":"'+y+'"};
san.events.push(k);

here is solution for this problem. 这是解决这个问题的方法。

san = {"events": [
{"event_id": "1", "event_name": "Breakfast"},
{"event_id": "1", "event_name": "Calling Bob"}
]};
var x=2; var y='am';
k={"event_id":"x","event_name":y};
san.events.push(k);
console.log(san);

http://jsfiddle.net/3NSy8/ http://jsfiddle.net/3NSy8/

Does this work for you? 这对你有用吗?

x = "2";
y = "jam"
k= {"event_id": x, "event_name": y };
san.events.push(k);

Pass it inside a square bracket [ variable_name ]将其传递到方括号[ variable_name ]

Example:例子:

let account_name = "premium_account"
{"features": { [account_name] :"checked"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM