简体   繁体   English

使用 Nodejs 访问返回数据的属性

[英]Access the properties of a returned data using Nodejs

I want to access the age property of a returned Object in Nodejs and also be able to filter through it.我想在 Nodejs 中访问返回的 Object 的 age 属性,并且还能够对其进行过滤。

The Returned Oject返回的项目

{"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 ...

MY CODE我的代码

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);

});

Please can anyone help with it??请问有人可以帮忙吗??

I can now access it with this code, thanks to everyone.感谢大家,我现在可以使用此代码访问它。

but i wanto to collapse the logs to one integer, can anyone point it out to me?但我想将日志折叠到一个 integer,有人能指出来吗?

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);

});

If you want to access the age property you must verify if data is an object.如果要访问年龄属性,则必须验证数据是否为 object。

Because if the type of data is a string, data.age not defined.因为如果数据的类型是字符串, data.age没有定义。

You should use你应该使用

let dataParsed = JSON.parse(data)

Finally, dataParsed.age is defined.最后,定义dataParsed.age

If you have unexpected error use:如果您有意外错误,请使用:

JSON.parse(JSON.stringify(data))

Please check if you are looking something like this.请检查您是否正在寻找这样的东西。

 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=";"")));

This will generate the below result:这将产生以下结果:

 [
"58",
"64",
"47",
"68",
"76",
"79",
"29",
"32"
]
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);
});

If you want to get only the last integer that is the no of age property then you must move your code to 'end' event.如果您只想获取最后一个 integer 即 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);

});

This might be your solution:这可能是您的解决方案:

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);
    })
});

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

In Swift Language I was try.在 Swift 语言中我试过了。 I was decode the data then convert into json object.我正在解码数据,然后转换为 json object。

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)
}
}

Here's my take on this one这是我对这个的看法

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)
  })
});

You can manipulate your output array until you only get the only part that you really need, which are the numbers.您可以操作您的 output 阵列,直到您只获得您真正需要的唯一部分,即数字。 Then you can just easily filter that array by value and return the length of it.然后您可以轻松地按值过滤该数组并返回它的长度。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM