【问题标题】:Access the properties of a returned data using Nodejs使用 Nodejs 访问返回数据的属性
【发布时间】:2020-06-24 09:01:50
【问题描述】:

我想在 Nodejs 中访问返回对象的年龄属性 也可以通过它进行过滤。

归来的对象

{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32, key=k1SN5, age=88, key=4SCsU, age=65, key=q3kG6, age=33, key=MGQpf, age=13, key=Kj6xW, age=14, key=tg2VM, age=30, key=WSnCU, age=24, key=f1Vvz, age=46, key=dOS7A, age=72, key=tDojg, age=82, key=nZyJA, age=48, key=R8JTk, age=29, key=005Ot, age=66, key=HHROm, age=12, key=5yzG8, age=51, key=xMJ5D, age=38, key=TXtVu, age=82, key=Hz38B, age=84, key=WfObU, age=27, key=mmqYB, age=14, key=4Z3Ay, age=62, key=x3B0i, age=55, key=QCiQB, age=72, key=zGtmR, age=66, key=nlIN9, age=8, key=hKalB, age=50, key=Na33O, age=17, key=jMeXm, age=15, key=OO2Mc, age=32, key=hhowx, age=34, key=gLMJf, age=60, key=PblX6, age=66, key=8Vm5W, age=22, key=oZKd6, age=88, key=RXNfQ, age=
{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32, key=k1SN5, age=88 ...

我的代码

const https = require('https');

https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
  let {statusCode} = resp
  let contentType = resp.headers['content-type']
  resp.setEncoding('utf-8')
  let data = '';

  // parse json data here...
  resp.on('data', (d) => {
    data += d
    console.log(data)
  })
  resp.on("error", (e) => {
    console.log("error", e)
  })

  //console.log(resp);

});

请问有人可以帮忙吗?

【问题讨论】:

    标签: javascript node.js swift https


    【解决方案1】:

    请检查您是否看起来像这样。

    const response =  {"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32"}
    console.log(response.data.split(",").filter(data => !data.indexOf(" age=")).map(data => data.replace(" age=","")));

    这将产生以下结果:

     [
    "58",
    "64",
    "47",
    "68",
    "76",
    "79",
    "29",
    "32"
    ]
    

    【讨论】:

      【解决方案2】:

      感谢大家,我现在可以使用此代码访问它。

      但是我想把日志折叠成一个整数,有人能指出来吗?

      const https = require('https');
      
      https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
        let {statusCode} = resp
        let contentType = resp.headers['content-type']
        resp.setEncoding('utf-8')
        let data = '';
      
        // parse json data here...
        resp.on('data', (d) => {
          data += [d]
        })
      
          resp.on('end', () => {
          let parsedData = data.split(",")
          .filter(data =>!data.indexOf(" age="))
          .map(data => data.replace(" age=",""))
          .map(data => parseInt(data))
          .filter(data => {
           return (data >= 50);
          }).length
          console.log(parsedData);
        })
        resp.on("error", (e) => {
          console.log("error", e)
        })
      
        //console.log(resp);
      
      });
      

      【讨论】:

        【解决方案3】:

        如果你想访问年龄属性,你必须验证数据是否是一个对象。

        因为如果数据类型是字符串,data.age没有定义。

        你应该使用

        let dataParsed = JSON.parse(data)
        

        最后,dataParsed.age 被定义了。

        如果您遇到意外错误,请使用:

        JSON.parse(JSON.stringify(data))
        

        【讨论】:

          【解决方案4】:
          const response =  {"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76, key=IxKVQ, age=79, key=eD221, age=29, key=XZbHV, age=32"}
          const count = response.data.split(",").map(value=>value.split("=")).filter(value=> value[0]===" age").reduce((cumulative,current)=>{if(Number(current[1])>=50){ return cumulative+1}else{return cumulative}},0);
          console.log(count)
          

          【讨论】:

          • 请解释答案。仅代码的答案很难理解,而且从长远来看也不太有益。
          【解决方案5】:

          如果您只想获取最后一个整数,即 no of age 属性,那么您必须将代码移动到“结束”事件。

          const https = require('https');
          
            https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
             let {statusCode} = resp
             let contentType = resp.headers['content-type']
             resp.setEncoding('utf-8')
             let data = '';
          
            // parse json data here...
            resp.on('data', (d) => {
              data += [d]
            })
          
            resp.on('end', () => {
              let parsedData = data.split(",")
              .filter(data =>!data.indexOf(" age="))
              .map(data => data.replace(" age=",""))
              .map(data => parseInt(data))
              .filter(data => {
               return (data >= 50);
              }).length
              console.log(parsedData);
            })
            resp.on("error", (e) => {
              console.log("error", e)
            })
          
            //console.log(resp);
          
          });
          

          【讨论】:

            【解决方案6】:

            这可能是您的解决方案:

            const https = require('https');
            
            https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
              let data = ''
                resp.on('data', (chunk) => {
                  data+=chunk;
                });
                resp.on('end', () => {
                  let jsonData = JSON.parse(data.toString());
                  let actualData = jsonData.data;
                  let arr1 = actualData.split(", ");
                  let totalCount = 0;
                  for(let i = 0; i < arr1.length; i++){
                    let item = arr1[i];
                    if(item.indexOf('age=') !== -1){
                      let age = item.split('=');
                      if(parseInt(age[1]) >= 50) {
                        totalCount++;
                      }
                    }
                  }
                  console.log(totalCount);
                })
            });
            

            来源:https://amudalvi.blogspot.com/p/coderbyte-node-js-age-counting.html

            【讨论】:

              【解决方案7】:

              我尝试过使用 Swift 语言。我正在解码数据然后转换成 json 对象。

              struct DataObject: Decodable {
              let data: String
              }
              
              
              let jsonData = JSON.data(using: .utf8)!
              let dataObject: DataObject = try! JSONDecoder().decode(DataObject.self, from: jsonData)
               // print(dataObject.data)
              var count = 0
              for item in dataObject.data.split(separator: ","){
              let age = item.split(separator: "=")
              let stringAge =  age[0]
              
              if(stringAge == " age"){
                  //  print("String agae", stringAge)
                   let ageInt = age[1]
                  //  print("String agae Int ", ageInt)
                   if Int(String(ageInt))! >= 50){
                      count = count + 1 
                   }
                  // print("age and key",age)
              }
              }
              

              【讨论】:

                【解决方案8】:

                这是我对这个的看法

                const https = require('https');
                
                https.get('https://coderbyte.com/api/challenges/json/age-counting', (resp) => {
                  let data = '';
                
                  resp.on('data', (chunk) => {
                    data = data += chunk
                  })
                
                  resp.on('end',  () => {
                    let parsedData = JSON.parse(data.toString()).data
                    let arrayData = parsedData.split(", ")
                
                    let ageArray = [];
                    for (i = 0; i < arrayData.length; i++) {
                      if (i%2 === 1) {
                        ageArray.push(Math.floor(arrayData[i].slice(4)))
                      }
                    }
                
                    let filteredArray = ageArray.filter((item) => {
                      return item >= 50
                    })
                
                    console.log(filteredArray.length)
                  })
                });
                

                您可以操作您的输出数组,直到您只得到您真正需要的唯一部分,即数字。然后您可以轻松地按值过滤该数组并返回它的长度。

                【讨论】:

                  【解决方案9】:
                  const https = require("https");
                  var fs = require("fs");
                  const crypto = require("crypto");
                  
                  https.get("https://coderbyte.com/api/challenges/json/age-counting", (resp) => {
                    let { statusCode } = resp;
                    let contentType = resp.headers["content-type"];
                    resp.setEncoding("utf-8");
                    let data = "";
                  
                    // parse json data here...
                    resp.on("data", (d) => {
                      data += [d];
                    });
                    let array = [];
                    sortedArray = [];
                  
                    resp.on("end", () => {
                      newarray = JSON.parse(data).data.split(",");
                      array = [];
                      newarray.forEach((val, index) => {
                        if (!val.includes(" age=")) {
                          keyValue = val.replace(" key=", "");
                          keyValue = keyValue.replace("key=", "");
                          let age = newarray[index + 1].replace(" age=", "");
                          if (age > 32) {
                            sortedArray.push([keyValue]);
                            array.push({
                              [keyValue]: age,
                            });
                          }
                        }
                      });
                      const writeStream = fs.createWriteStream("output.txt");
                      const pathName = writeStream.path;
                      sortedArray.forEach((value) => writeStream.write(`${value}\n`));
                  
                      // the finish event is emitted when all data has been flushed from the stream
                      writeStream.on("finish", () => {
                        const fileBuffer = fs.readFileSync("output.txt");
                        const hashSum = crypto.createHash("sha256");
                        hashSum.update(fileBuffer);
                        const hex = hashSum.digest("hex");
                        console.log(hex);
                      });
                  
                      // handle the errors on the write process
                      writeStream.on("error", (err) => {
                        console.error(`There is an error writing the file ${pathName} => ${err}`);
                      });
                  
                      // close the stream
                      writeStream.end();
                    });
                  
                    //console.log(resp);
                  });
                  

                  【讨论】:

                  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
                  猜你喜欢
                  • 1970-01-01
                  • 2013-11-10
                  • 1970-01-01
                  • 2012-12-18
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-12-21
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多