简体   繁体   English

如何在带有字符串对象的parseJson函数中使用变量?

[英]How to use variable in parseJson function with string objects?

I am using three objects in parseJson function and I want to use a variable inside them. 我在parseJson函数中使用了三个对象,我想在其中使用一个变量。 How I can merge a variable with the value of one object? 如何合并一个对象的值与变量? Or is there any way to use third object and save variable to that object? 还是有什么方法可以使用第三个对象并将变量保存到该对象?

var firstQ = "This need to be merge.";

var jsondata = $.parseJSON('[{"q": "Question 1", "p": "Answer 1"+"firstQ"}]');

This will insert your variable into the jsondata 这会将您的变量插入jsondata

 var firstQ = "This need to be merge."; var str = '[{"q": "Question 1", "p": "Answer 1: ' + firstQ + '"}]'; //var jsondata = $.parseJSON(str) console.log(str) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Just to clarify, are you trying to figure out how to create a JSON object of this structure: 只是为了澄清一下,您是否正在尝试弄清楚如何创建这种结构的JSON对象:

{"q": someString, "p": someOtherString+someOtherString2} ? {“ q”:someString,“ p”:someOtherString + someOtherString2}?

If so, you can do this: 如果是这样,您可以这样做:

{"q": "Question 1", "p": "Answer 1"+firstQ}

Don't forget to add a space if it is needed. 如果需要,请不要忘记添加一个空格。

Example: 例:

 let firstQ = "This need to be merge."; var jsonData = {"q": "Question 1", "p": "Answer 1 "+firstQ}; console.log(jsonData); 

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

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