[英]Access the properties of a returned data using Nodejs
我想在 Nodejs 中訪問返回的 Object 的 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, 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);
});
請問有人可以幫忙嗎??
感謝大家,我現在可以使用此代碼訪問它。
但我想將日志折疊到一個 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);
});
如果要訪問年齡屬性,則必須驗證數據是否為 object。
因為如果數據的類型是字符串, data.age
沒有定義。
你應該使用
let dataParsed = JSON.parse(data)
最后,定義dataParsed.age
。
如果您有意外錯誤,請使用:
JSON.parse(JSON.stringify(data))
請檢查您是否正在尋找這樣的東西。
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"
]
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);
});
如果您只想獲取最后一個 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);
});
這可能是您的解決方案:
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
在 Swift 語言中我試過了。 我正在解碼數據,然后轉換為 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)
}
}
這是我對這個的看法
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)
})
});
您可以操作您的 output 陣列,直到您只獲得您真正需要的唯一部分,即數字。 然后您可以輕松地按值過濾該數組並返回它的長度。
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.