【问题标题】:JSON file with different key names具有不同键名的 JSON 文件
【发布时间】:2023-02-11 15:46:35
【问题描述】:

我将 MongoDb 与 mongoose 库一起使用。我的架构是英文的,但我收到的结构与德语(或其他)关键字相同。

MongoDB 架构:

{
  "Uid": Number,
  "User": {
    "Firstname": String,
    "Lastname": String
  }
}

JSON对象:

"Uid": Number,
"Benutzer": {
  "Vorname": String,
  "Nachname": String
}

我正在接收作为字符串的 JSON 对象,我正在使用 JSON.parse,realObject 更复杂,我不想逐字段复制。如果关键字相同,我可以使用简单的赋值:

const my_object = JSON.parse(file_as_string)
MyObject.findOneAndUpdate(
  { UID: my_object.Uid},
  {
    User: my_object.Benutzer
  })

我的问题是:如何将 JSON(带有德语关键字)转换为带有英语关键字的模式?

【问题讨论】:

  • json(德语或任何其他语言)是否始终有效并且具有相同的长度/大小?还是需要验证完整性?为什么 mongodb 中的 Uid 是字符串而 json 中是数字?
  • JSON 有效且具有相同的长度/大小,mongodb 中的 Uid 和 JSON 中的 Uid 是展位号,对此感到抱歉。
  • 那么你的问题是什么?
  • 如何将 JSON(带有德语关键字)转换为带有英语关键字的模式?
  • 请发布完整的 json 示例。

标签: node.js json mongodb mongoose


【解决方案1】:

您可能需要深度克隆您的对象并在此过程中翻译属性名称。

let translations = { 
      "Benutzer": "User", 
      "Vorname": "Firstname", 
      "Nachname": "Lastname", 
      "Strasze": "Street",
      "PLZ": "ZIP",
      "Ort": "City",
      "Nummer": "Number"
}


function deepClone(data) {
  //For arrays deepclone every element in the array  
  if (Array.isArray(data)) {
    return data.map(d => deepClone(d));
  }

  //For object deepclone every property and translate the property's name
  //Fallback on the original name, if no translation is found
  if (typeof data === "object") {
    let result = {}
    for (let key in data) {
      result[translations[key]||key] = deepClone(data[key]);
    }
    return result;
  }

  //return primitive datatypes (number, string, bool) as they are
  return data;
}
    
let g = { 
  Uid: 1, //this one is not gonna be translated because there is no translation entry
  Benutzer: { 
    Vorname: "Papa", 
    Nachname: "Schlumpf", 
    Adressen: [  //this one is not gonna be translated because there is no translation entry
      { Strasze: "Hauptstraße", Nummer: 1, PLZ: "1234", Ort: "Schlumpfhausen" },
      { Strasze: "Hauptplatz", Nummer: 17, PLZ: "1235", Ort: "Gargamelsdorf" }
    ]
  }
};

console.log(deepClone(g));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2023-04-10
    • 1970-01-01
    • 2014-02-17
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多