英文:
How do I access second level JSON values in JavaScript
问题
I am trying to use JSON data from a HTTPS request to fill parameters based on the request however I keep coming across the same error:
> index.js:45
> value: request.body.header.value
> ^
>
> TypeError: Cannot read properties of undefined (reading 'value')
我试图使用来自HTTPS请求的JSON数据来填充基于请求的参数,但我一直遇到相同的错误:
> index.js:45
> value: request.body.header.value
> ^
>
> TypeError: Cannot read properties of undefined (reading 'value')
I seem to have no trouble with accessing the first layer items, however I cannot work around the above error for anything past the first level.
Here is what my script looks like so far:
看起来我没有问题访问第一层项目,但是对于超出第一层的任何内容,我似乎无法解决上述错误。以下是到目前为止我的脚本的样子:
const functions = require("firebase-functions");
const { PKPass } = require("passkit-generator");
const admin = require("firebase-admin");
var fs = require("file-system");
var path = require("path");
var axios = require("axios");
admin.initializeApp(functions.config().firebase);
var storageRef = admin.storage().bucket()
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return "rgb(" + r + ", " + g + ", " + b + ")";
}
exports.pass = functions.https.onRequest((request, response) => {
PKPass.from({
model: "./model/BoardingPass.pass",
certificates: {
wwdr: fs.fs.readFileSync("./certs/wwdr.pem"),
signerCert: fs.fs.readFileSync("./certs/passIdentifierSignerCert.pem"),
signerKey: fs.fs.readFileSync("./certs/passIdentifierSignerKey.pem"),
signerKeyPassphrase: "PASSPHRASE"
},
},
{
authenticationToken: "AUTHTOKEN",
webServiceURL: "WEBSERVICEURL",
serialNumber: request.body.serialNumber,
description: request.body.description,
logoText: request.body.logoText,
foregroundColor: hexToRgb("#" + request.body.foregroundColour),
backgroundColor: hexToRgb("#" + request.body.backgroundColour)
})
.then(async (newPass) => {
newPass.headerFields.push(
{
key: "gate",
label: "GATE",
value: request.body.header.value
}
)
newPass.primaryFields.push(
{
key: "depart",
label: request.body.primary[0].label,
value: request.body.primary[0].value
},
{
key: "arrive",
label: request.body.primary[1].label,
value: request.body.primary[1].value
}
)
newPass.secondaryFields.push(
{
key: "passenger",
label: "PASSENGER",
value: request.body.secondary.value
}
)
newPass.auxiliaryFields.push(
{
key: "boardingTime",
label: "DEPART",
value: request.body.auxiliary[0].value
},
{
key: "flightNewName",
label: "FLIGHT",
value: request.body.auxiliary[1].value
},
{
key: "class",
label: "CLASS",
value: request.body.auxiliary[2].value
},
{
key: "date",
label: "DATE",
value: request.body.auxiliary[3].value
}
)
newPass.backFields.push(
{
key: "passport",
label: "PASSPORT",
value: request.bodyback[0].value
},
{
key: "residence",
label: "RESIDENCE",
value: request.body.back[1].value
}
)
newPass.setBarcodes({
message: request.body.barcode,
format: "PKBarcodeFormatPDF417",
messageEncoding: "iso-8859-1"
})
const resp = await axios.get(request.body.thumbnail, { responseType: 'arraybuffer' })
const buffer = Buffer.from(resp.data, "utf-8")
newPass.addBuffer("thumbnail.png", buffer)
newPass.addBuffer("thumbnail@2x.png", buffer)
const bufferData = newPass.getAsBuffer();
fs.writeFileSync("new.pkpass", bufferData)
storageRef.file("passes/boardingPass.pkpass")
.save(bufferData, (error) => {
if (!error) {
console.log("Pass was uploaded successfully.");
response.status(200);
}
else {
console.log("There was an error uploading pass");
response.status(400);
}
})
})
});
And this is the HTTPS POST request:
这是HTTPS POST请求:
{
"barcode": "TESTBARCODE",
"thumbnail": "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png",
"serialNumber": "TESTSERIAL",
"description": "TESTDESCRIPTION",
"logoText": "TESTLOGOTEXT",
"foregroundColour": "#FFFFFF",
"backgroundColour": "#000000",
"header": [{
"value": "21"
}],
"primary": [
{
"
<details>
<summary>英文:</summary>
I am trying to use JSON data from a HTTPS request to fill parameters based on the request however I keep coming across the same error:
> index.js:45
> value: request.body.header.value
> ^
>
> TypeError: Cannot read properties of undefined (reading 'value')
I seem to have no trouble with accessing the first layer items, however I cannot work around the above error for anything past the first level.
Here is what my script looks like so far:
const functions = require("firebase-functions");
const { PKPass } = require("passkit-generator");
const admin = require("firebase-admin");
var fs = require("file-system");
var path = require("path");
var axios = require("axios");
admin.initializeApp(functions.config().firebase);
var storageRef = admin.storage().bucket()
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return "rgb(" + r + ", " + g + ", " + b + ")";
}
exports.pass = functions.https.onRequest((request, response) => {
PKPass.from({
model: "./model/BoardingPass.pass",
certificates: {
wwdr: fs.fs.readFileSync("./certs/wwdr.pem"),
signerCert: fs.fs.readFileSync("./certs/passIdentifierSignerCert.pem"),
signerKey: fs.fs.readFileSync("./certs/passIdentifierSignerKey.pem"),
signerKeyPassphrase: "PASSPHRASE"
},
},
{
authenticationToken: "AUTHTOKEN",
webServiceURL: "WEBSERVICEURL",
serialNumber: request.body.serialNumber,
description: request.body.description,
logoText: request.body.logoText,
foregroundColor: hexToRgb("#" + request.body.foregroundColour),
backgroundColor: hexToRgb("#" + request.body.backgroundColour)
})
.then(async (newPass) => {
newPass.headerFields.push(
{
key: "gate",
label: "GATE",
value: request.body.header.value
}
)
newPass.primaryFields.push(
{
key: "depart",
label: request.body.primary[0].label,
value: request.body.primary[0].value
},
{
key: "arrive",
label: request.body.primary[1].label,
value: request.body.primary[1].value
}
)
newPass.secondaryFields.push(
{
key: "passenger",
label: "PASSENGER",
value: request.body.secondary.value
}
)
newPass.auxiliaryFields.push(
{
key: "boardingTime",
label: "DEPART",
value: request.body.auxiliary[0].value
},
{
key: "flightNewName",
label: "FLIGHT",
value: request.body.auxiliary[1].value
},
{
key: "class",
label: "CLASS",
value: request.body.auxiliary[2].value
},
{
key: "date",
label: "DATE",
value: request.body.auxiliary[3].value
}
)
newPass.backFields.push(
{
key: "passport",
label: "PASSPORT",
value: request.bodyback[0].value
},
{
key: "residence",
label: "RESIDENCE",
value: request.body.back[1].value
}
)
newPass.setBarcodes({
message: request.body.barcode,
format: "PKBarcodeFormatPDF417",
messageEncoding: "iso-8859-1"
})
const resp = await axios.get(request.body.thumbnail, { responseType: 'arraybuffer' })
const buffer = Buffer.from(resp.data, "utf-8")
newPass.addBuffer("thumbnail.png", buffer)
newPass.addBuffer("thumbnail@2x.png", buffer)
const bufferData = newPass.getAsBuffer();
fs.writeFileSync("new.pkpass", bufferData)
storageRef.file("passes/boardingPass.pkpass")
.save(bufferData, (error) => {
if (!error) {
console.log("Pass was uploaded successfully.");
response.status(200);
}
else {
console.log("There was an error uploading pass");
response.status(400);
}
})
})
});
And this is the HTTPS POST request:
{
"barcode": "TESTBARCODE",
"thumbnail": "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png",
"serialNumber": "TESTSERIAL",
"description": "TESTDESCRIPTION",
"logoText": "TESTLOGOTEXT",
"foregroundColour": "#FFFFFF",
"backgroundColour": "#000000",
"header": [{
"value": "21"
}],
"primary": [
{
"label": "Melbourne",
"value": "MEL"
},
{
"label": "Singapore",
"value": "SNG"
}
],
"secondary": {
"value": "TEST PASSENGER NAME"
},
"auxiliary": [
{
"value": "11:59 PM"
},
{
"value": "999"
},
{
"value": "Economy"
},
{
"value": "1/12"
}
],
"back": [
{
"value": "COUNTRY"
},
{
"value": "1 Flinders Street, Melbourne, Victoria, 3000"
}
]
}
Regardless of what is after `response.body.*.<HERE>` the same error occurs.
</details>
# 答案1
**得分**: 2
`request.body.header` 看起来像一个数组,而不是一个对象>
```json
"header": [{
"value": "21"
}],
所以也许你需要索引到数组中找到 value
:
request.body.header[0].value
英文:
request.body.header
looks like an array, not an object>
"header": [{
"value": "21"
}],
So maybe you need to index into the array to find value
:
request.body.header[0].value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论