javascript 如何连接字符串和数字以制作 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46519339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concatenate string and numbers to make a JSON object?
提问by user2109581
I want to make a JSON object like this:
我想制作一个这样的 JSON 对象:
let lob = { courses_dept: 'sci', courses_avg: 77.09 };
by concatenate variables together:
通过将变量连接在一起:
var dept = "sci";
var avg = 77.09;
let a = '{"courses_dept": dept, "courses_averge": avg }';
but I got SyntaxError if I do this:
但如果我这样做,我会得到 SyntaxError:
let b = JSON.parse(a);
What is the proper way to do this?
这样做的正确方法是什么?
回答by surjikal
If you want to use strings:
如果要使用字符串:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that deptis a string. If you don't know this in advance, wrap each variable with JSON.stringify:
这假设它dept是一个字符串。如果您事先不知道这一点,请将每个变量包装为JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
请注意,该字符串使用反引号 ` 而不是常规引号。这允许您进行字符串插值。如果你想直接连接,你可以使用 + 。
You can also just do a regular object:
你也可以只做一个普通的对象:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)
回答by surjikal
Why not just plain jsonobject then?
为什么不只是简单的json对象呢?
var dept = "sci";
var avg = 77.09;
let a = {
"courses_dept": dept,
"courses_averge": avg
};
console.log('a', a);
回答by user2109581
This way works and seems to be simpler.
这种方式有效,而且似乎更简单。
let b = {};
b["courses_dept"] = dept;
b["courses_averge"] = avg;
回答by YoJey Thilipan
you can make a json with single qouates and concatenate variable. After that you can parse the string
您可以使用单个 qouates 和连接变量制作 json。之后,您可以解析字符串
var id_of_the_product = $('#is-a-gift').data( 'gift_product_id' ) ;
var items_in_cart = (cart_item_count) - (gift_wraps_in_cart);
$.ajax({
type: 'POST',
url: '/cart/update.js',
data: JSON.parse('{ "updates": { "'+ id_of_the_product +'" : "'+items_in_cart+'" }, "attributes": { "gift-wrapping": "'+gift_wrapping_type+'" } }'),
dataType: 'json',
success: function() { }
});

