【问题标题】:How to access the given json in javascript? [duplicate]如何在javascript中访问给定的json? [复制]
【发布时间】:2018-09-12 08:04:29
【问题描述】:

如何访问下面给出的这个 json 结构?

{
   "question":{
      "119380":{
         "email":{
            "-L8o-zzRRTOJQjI4BQZ0":"abc@gmail.com",
            "-L8odhdW2xAnayboUb8h":"abc@gmail.com",
            "-L8ouI_wt8hb_R0GvXZ5":"abc@gmail.com",
            "-L8p8b03ZpoKUQiYU_69":"abc@gmail.com"
         }
      },
      "123541":{
         "email":{
            "-L8whdSxfPa1DGXwtTuD":"abc@gmail.com"
         }
      },

   }
}

我正在尝试以下方式

 exports.sendspamalertNotification = functions.database
.ref("spam/question").onWrite(event => {
  const original = event.data.val();
  console.log(event.data.val());

一切都在控制台中打印,但我如何访问每个 question_id(数字字符串)和该 question_id(数字字符串)下的电子邮件?

其实我是新手,所以如果它的愚蠢问题请见谅!

请提供一些解决方案!

【问题讨论】:

  • 你试过什么?什么不工作
  • 实际上我卡住了,因为没有名称可以访问这个数字字符串,而且这个数字字符串(基本上是一个 question_id)每次都会改变! @菲尔
  • 并且数字字符串每次肯定都是唯一的。
  • 我在这里发布的这个 json 结构来自控制台,我无法使用它,因为您在 sn-p 中显示。 @Mohammad Ali Rony
  • exports.sendNotification = functions.database .ref("leads/{push_Id}").onWrite(event => { const original = event.data.val(); const email = event.data .val().email const location = event.data.val().location 这是另一个运行良好的代码示例。这样我需要访问但没有标题可以访问数字字符串?跨度>

标签: javascript jquery json google-cloud-functions


【解决方案1】:

使用方括号访问其字符串在点表示法中无效的属性:

const someObj = {
  "question": {
    "119380": {
      "email": {
        "-L8o-zzRRTOJQjI4BQZ0": "abc@gmail.com",
      }
    }
  }
}
console.log(someObj.question[119380].email);

【讨论】:

  • 请投票关闭此类重复
  • TypeError: 无法读取 export.sendspamalertNotification.functions.database.ref.onWrite.event (/user_code/index.js:854:32) at /user_code/node_modules/ 处未定义的属性“119380” firebase-functions/lib/cloud-functions.js:54:20 at process._tickDomainCallback (internal/process/next_tick.js:135:7) 当我尝试这个时出现上述错误-exports.sendspamalertNotification = functions.database .ref ("垃圾邮件/问题").onWrite(event => { const original = event.data.val(); console.log(original.question[119380].email); @CertainPerformance
【解决方案2】:

您可以使用此代码访问动态密钥 JSON。

var obj = JSON.parse('{"question" : {"119380" : {"email" : {"-L8o-zzRRTOJQjI4BQZ0" : "abc@gmail.com", "-L8odhdW2xAnayboUb8h" : "abc@gmail.com","-L8ouI_wt8hb_R0GvXZ5" : "abc@gmail.com","-L8p8b03ZpoKUQiYU_69" : "abc@gmail.com"}},"123541" : {"email" : {"-L8whdSxfPa1DGXwtTuD" : "abc@gmail.com"}}}}');
Object.keys(obj.question).forEach(function(questionKey){
    var question = obj.question[questionKey];
    console.dir(question);
    Object.keys(question.email).forEach(function(emailKey){
        var value = question.email[emailKey];
        console.dir( question.email[emailKey]);
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多