String a = {"id":"cszb1","value":"999"},{"id":"cszbzd2","value":"999"},转json
时间: 2023-10-27 16:06:57 浏览: 103
这里提供一种C++的方法将字符串转换为JSON格式:
```
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <map>
using namespace std;
string escape(string const& s) {
ostringstream o;
for (auto c : s) {
switch (c) {
case '"': o << "\\\""; break;
case '\\': o << "\\\\"; break;
case '\b': o << "\\b"; break;
case '\f': o << "\\f"; break;
case '\n': o << "\\n"; break;
case '\r': o << "\\r"; break;
case '\t': o << "\\t"; break;
default:
if ('\x00' <= c && c <= '\x1f') {
o << "\\u" << hex << setw(4) << setfill('0') << static_cast<int>(c);
} else {
o << c;
}
}
}
return o.str();
}
string to_json(string const& s) {
return '"' + escape(s) + '"';
}
string to_json(int n) {
return to_string(n);
}
string to_json(double d) {
ostringstream o;
o << d;
return o.str();
}
template <typename T>
string to_json(vector<T> const& v) {
ostringstream o;
o << '[';
bool first = true;
for (auto const& e : v) {
if (!first) {
o << ',';
}
first = false;
o << to_json(e);
}
o << ']';
return o.str();
}
template <typename K, typename V>
string to_json(map<K, V> const& m) {
ostringstream o;
o << '{';
bool first = true;
for (auto const& p : m) {
if (!first) {
o << ',';
}
first = false;
o << to_json(p.first) << ':' << to_json(p.second);
}
o << '}';
return o.str();
}
int main() {
string a = R"([{"id":"cszb1","value":"999"},{"id":"cszbzd2","value":"999"}])";
vector<map<string, string>> v;
size_t i = 0;
while (i < a.size()) {
size_t j = a.find_first_of("{[", i);
if (j == string::npos) {
break;
}
size_t k = a.find_first_of("}]", j);
if (k == string::npos) {
break;
}
string s = a.substr(j, k - j + 1);
map<string, string> m;
size_t l = 0;
while (l < s.size()) {
size_t p = s.find_first_of(":\"", l);
if (p == string::npos) {
break;
}
size_t q = s.find_first_of("\",}", p + 1);
if (q == string::npos) {
break;
}
string key = s.substr(l + 1, p - l - 2);
string value = s.substr(p + 2, q - p - 2);
m[key] = value;
l = q + 1;
}
v.push_back(m);
i = k + 1;
}
cout << to_json(v) << endl;
return 0;
}
```
这个程序将字符串a解析为一个vector,其中每个元素都是一个map,map的key是字符串"id"和"value",value是字符串"999"。然后,使用to_json函数将vector转换为JSON格式的字符串。
阅读全文