c++ - 如何在不更改 C++ 中的值的情况下更改 json 对象名称?
问题描述
我正在将 json 用于现代 C++。我有一个 json 文件,其中包含一些数据,例如:
{
"London": {
"Adress": "londonas iela 123",
"Name": "London",
"Shortname": "LL"
},
"Riga": {
"Adrese": "lidostas iela 1",
"Name": "Riga",
"Shortname": "RIX"
}
我找到了一种修改“Adrese”、“Name”、“Shortname”值的方法。如您所见,我将“名称”和关键元素名称设置为相同的东西。
但我需要更改关键元素和值“名称”。
所以最后当我以某种方式在代码中修改它时,它看起来像:
{
"Something_New": {
"Adress": "londonas iela 123",
"Name": "Something_New",
"Shortname": "LL"
},
"Riga": {
"Adrese": "lidostas iela 1",
"Name": "Riga",
"Shortname": "RIX"
}
我试过了:
/other_code/
json j
/functions_for_opening_json file/
j["London"]["Name"] = "Something_New"; //this changes the value "name"
j["London"] = "Something_New"; //But this replaces "London" with
"Something_new" and deletes all of its inside values.
然后我尝试了类似的东西:
for(auto& el : j.items()){
if(el.key() == "London"){
el.key() = "Something_New";}
}
但这也没有用。
我想要 j["London"] = "Something_new" 之类的东西,并让它保留原来为 "London" 的所有值。
解决方案
与键“London”关联的值是包含其他 3 个键及其值的整个子树 json 对象。此行j["London"] = "Something_New";
不会更改键“London”,而是更改其值。所以你最终得到一对“伦敦”:“新事物”,覆盖了 json 子树对象。密钥在内部存储为 std::map 。因此,您不能简单地重命名这样的键。尝试:
void change_key(json &j, const std::string& oldKey, const std::string& newKey)
{
auto itr = j.find(oldKey); // try catch this, handle case when key is not found
std::swap(j[newKey], itr.value());
object.erase(itr);
}
进而
change_key(j, "London", "Something_New");
推荐阅读
- reactjs - 如何修改 react-datetime 的输出
- java - 如何在 Groovy(或 Java)中将字符串数组的所有索引包含在一行中
- asp.net - 您能否在集成测试中使用内存中的 HttpServer 托管旧版 ASP.NET MVC 控制器
- excel - 多个日期范围的 IF 语句
- excel - Excel VBA宏根据提取的单元格值循环、复制、粘贴、偏移
- azure - Azure 文件共享 Active Directory 身份验证方法
- mysql - ActiveRecord::Base.sanitize_sql_array 插入的引号导致无效的 SQL
- function - Learndash 在注册时重置课程/测验进度
- go - Terraform 自定义提供程序 GPG 问题
- express - 如何使用 Jest 和 NestJS 模拟 Express Response 发送?