如何在JavaScript中访问第二级JSON值

huangapple go评论75阅读模式
英文:

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": [
        {
            &quot

<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 &quot;rgb(&quot; + r + &quot;, &quot; + g + &quot;, &quot; + b + &quot;)&quot;;

}

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) =&gt; {
    newPass.headerFields.push(
        {
            key: &quot;gate&quot;,
            label: &quot;GATE&quot;,
            value: request.body.header.value
        }
    )
    newPass.primaryFields.push(
        {
            key: &quot;depart&quot;,
            label: request.body.primary[0].label,
            value: request.body.primary[0].value
        },
        {
            key: &quot;arrive&quot;,
            label: request.body.primary[1].label,
            value: request.body.primary[1].value
        }
    )
    newPass.secondaryFields.push(
        {
            key: &quot;passenger&quot;,
            label: &quot;PASSENGER&quot;,
            value: request.body.secondary.value
        }
    )
    newPass.auxiliaryFields.push(
        {
            key: &quot;boardingTime&quot;,
            label: &quot;DEPART&quot;,
            value: request.body.auxiliary[0].value
        },
        {
            key: &quot;flightNewName&quot;,
            label: &quot;FLIGHT&quot;,
            value: request.body.auxiliary[1].value
        },
        {
            key: &quot;class&quot;,
            label: &quot;CLASS&quot;,
            value: request.body.auxiliary[2].value
        },
        {
            key: &quot;date&quot;,
            label: &quot;DATE&quot;,
            value: request.body.auxiliary[3].value
        }
    )
    newPass.backFields.push(
        {
            key: &quot;passport&quot;,
            label: &quot;PASSPORT&quot;,
            value: request.bodyback[0].value
        },
        {
            key: &quot;residence&quot;,
            label: &quot;RESIDENCE&quot;,
            value: request.body.back[1].value
        }
    )

    newPass.setBarcodes({
        message: request.body.barcode,
        format: &quot;PKBarcodeFormatPDF417&quot;,
        messageEncoding: &quot;iso-8859-1&quot;
    })

    const resp = await axios.get(request.body.thumbnail, { responseType: &#39;arraybuffer&#39; })
    const buffer = Buffer.from(resp.data, &quot;utf-8&quot;)
    newPass.addBuffer(&quot;thumbnail.png&quot;, buffer)
    newPass.addBuffer(&quot;thumbnail@2x.png&quot;, buffer)
    const bufferData = newPass.getAsBuffer();
    fs.writeFileSync(&quot;new.pkpass&quot;, bufferData)
    storageRef.file(&quot;passes/boardingPass.pkpass&quot;)
        .save(bufferData, (error) =&gt; {
            if (!error) {
                console.log(&quot;Pass was uploaded successfully.&quot;);
                response.status(200);
            }
            else {
                console.log(&quot;There was an error uploading pass&quot;);
                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.*.&lt;HERE&gt;` the same error occurs.

</details>


# 答案1
**得分**: 2

`request.body.header` 看起来像一个数组,而不是一个对象&gt;

```json
"header": [{
    "value": "21"
}],

所以也许你需要索引到数组中找到 value:

request.body.header[0].value
英文:

request.body.header looks like an array, not an object>

    &quot;header&quot;: [{
        &quot;value&quot;: &quot;21&quot;
    }],

So maybe you need to index into the array to find value:

request.body.header[0].value

huangapple
  • 本文由 发表于 2023年6月5日 20:00:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定