简体   繁体   English

如何使用变量作为原始JSON字符串中的数据?

[英]How do you use variables as data in a raw JSON string?

I'm working with an API in C++ that uses raw JSON strings. 我正在使用使用原始JSON字符串的C ++ API。 For example: 例如:

string data = R"JSON({
            "key1": "value1",
            "key2": "value2"
        })JSON";

I would like to be use variables as the values. 我想将变量用作值。 For example: 例如:

string value1 = "55.2";
string value2 = "3.14";

string data = R"JSON({
            "key1": value1,  //somehow use the string variables here
            "key2": value2
        })JSON";

Is anything like this possible? 这样有可能吗?

You can concatenate strings by using operator+ . 您可以使用operator+连接字符串。

#include <iostream>
#include <string>

int main() {
    std::string value = "55.2";
    std::string str = R"({"key1":)" + value + "}";
    std::cout << str;
}

If you just need to do it once, you can follow the suggestion from the other answers/comments and concatenate the resulting string manually. 如果您只需要执行一次,则可以遵循其他答案/评论的建议,并手动将结果字符串连接起来。

If you might need to do something more than that (eg build the huge JSON request for some network API, or parse the huge response back), keep reading :) 如果您可能还需要做更多的事情(例如,为某个网络API构建巨大的JSON请求,或者将巨大的响应解析回去),请继续阅读:)

I strongly dislike the idea of concatenating JSON manually using string operator+ , string streams, sprintf , or any other string operations. 我强烈不喜欢使用字符串operator+ ,字符串流, sprintf或任何其他字符串操作手动连接JSON的想法。

Any solution based on string concatenation might work when you work with numbers only and when your JSON is small, but if you ever need to concatenate string values into JSON, you get in trouble as soon as you have a " or a \\ character in your string. You'll need to do proper escaping. Also, if the JSON object you concatenate grows large, maintaining that code would be a nightmare. 基于字符串连接的任何解决方案时,你只和数字工作可能工作时,你的JSON虽小,但如果你需要连接字符串值成JSON,你有麻烦尽快得到您的一个"\\字符您字符串,您需要进行适当的转义,而且,如果串联的JSON对象变大,那么维护该代码将是一场噩梦。

Solutions? 解决方案?

If you need to use C++, find a library that does JSON operations for you. 如果需要使用C ++,请找到一个为您执行JSON操作的库。 There are plenty . 很多 It's often better to use the tested third-party code that solves this particular task well. 通常最好使用经过测试的第三方代码来很好地解决此特定任务。 Yes, it might take more time to start using an external dependency than concatenating the string manually, but it just makes the code better. 是的,开始使用外部依赖关系可能比手动连接字符串花费更多时间,但这只是使代码更好。

If your task is heavily related to calling network APIs and manipulating JSONs, C++ might not be the best language of choice for that, unless there are other considerations (or unless it's a programming assignment :) ). 如果您的任务与调用网络API和操作JSON密切相关,那么C ++可能不是最佳选择语言,除非有其他考虑(或除非是编程任务:))。 Modern scripting languages (Python, JavaScript, moth others) support JSON and network calls natively. 现代脚本语言(Python,JavaScript和其他语言)本地支持JSON和网络调用。

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

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