NodeJS 阅读文件后无法解析JSON

rt4zxlrg  于 2023-01-01  发布在  Node.js
关注(0)|答案(2)|浏览(157)

我试图读取存储在文件中的SNS主题以查询键值。我一直收到错误:
'测试正则表达式ts:8:45-错误TS2339:类型"string"上不存在属性"Records"。
8常量消息文本= JSON.解析(数据.记录[0].传感器.消息.消息); '
文件中的值确实存在,但是readFile()模块中的某些东西不允许在JSON.parse()中转换字符串。
下面是代码:

import { readFileSync, promises as fsPromises, readFile } from "fs";

readFile("./regex", "utf-8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  const messageText = JSON.parse(data.Records[0].Sns.Message.message);
  console.log(messageText);
});

数据文件格式和内容(regex):

"Records": [
        {
            "EventSource": "aws:sns",
            "EventVersion": "1.0",
            "EventSubscriptionArn": "arn:aws:sns:us-west-2:123456789012:Opsgenie_Alert_Messages_Prod:11g22y11-dd9e-4e40-a17c-d1111111111",
            "Sns": {
                "Type": "Notification",
                "MessageId": "5885272a-55d5-5c91-bf15-5b0253cab710",
                "TopicArn": "arn:aws:sns:us-west-2:123456789012:Opsgenie_Alert_Messages_Prod",
                "Subject": null,
                "Message": "{\"integrationName\":\"AmazonSNS (Outgoing)\",\"alert\":{\"alertId\":\"182374692817346129837\",\"message\":\"[AS] foobar_TEST on 10.00.0.00 has late Task Agent Jobs on TSTSRVR - Notification 8.9.3.11\",\"tags\":[\"alerts_as8\"],\"tinyId\":\"20000\",\"source\":\"35.00.000.0\",\"entity\":\"\",\"alias\":\"0baba525-5c10-41f0-b480-1293c2900c53_late_120\",\"createdAt\":1672348639658,\"updatedAt\":1672348640358000000,\"username\":\"Alert API\",\"userFullName\":\"Alert API\",\"description\":\"Last Status Message (from DB):\\nProcessing queue subscription...\\n\\nScheduled Start Time:\\n2022-12-29T08:00:00\\n\\nLast Heartbeat Time:\\n2022-12-29T10:00:00.293\\n\\nHelpful links: \\n[Graylog](http://graylog.companyname.local/)\\n\\nThese links rely on naming conventions and might be incorrect:\\n\\n[Log File](http://graylog.companyname.local/search?q=institution%3Afakesiteuri_TEST+AND+TA_Log_File%3ANotification%5C%5C2022%5C-12%5=%%C-29%5C-08_00_23.log&rangetype=relative&relative=17777)\\n\\n[Site]( https://www.companyname.com/some_TEST/Logon.aspx?nosso= )\\n\\n\\n{AgentURL=taskagent://TSTTSK50:7640,Version=8.9.3.11, Database=DB_TESTsites\":{\"AgentURL\":\"taskagent://TSTTSK50:7640\",\"AstraVersion\":\"8.9.3.11\",\"Database\":\"l}}",
                "Timestamp": "2022-12-29T21:17:19.913Z",
                "SignatureVersion": "1",
                "Signature": "<SomeValueHere>",
                "SigningCertUrl": "https:*.pem",
                "UnsubscribeUrl": "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-:Opsgenie_Alert_Messages_Prod:",
                "MessageAttributes": {}
            }
        }
    ]

我尝试在第一个节点(data)中查询对象,结果打印出来了。当我尝试添加第二个节点(Records [0])时,它出错了。
我希望能够使用JSON.parse()查询对象,并将值存储到变量中。

nxagd54h

nxagd54h1#

代码甚至在尝试解析JSON之前就失败了。
像这样的怎么样?

import { readFileSync, promises as fsPromises, readFile } from 'fs';

readFile('./regex', 'utf-8', (err, data) => { 
  if(err) { 
    console.error(err); 
  } else { 
    const parsedData = JSON.parse(data);     
    const messageText = parsedData.Records[0].Sns.Message.message;     
    console.log(messageText);
  }
});
knpiaxh1

knpiaxh12#

感谢Matj和Ol234让我走上正轨!
我错过了在解析内部JSON字符串(Records[0].Sns.Message)之前解析外部JSON字符串(regex文件)的步骤。
下面是工作代码:

import { readFileSync, promises as fsPromises, readFile } from 'fs';

readFile('./regex', 'utf-8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  // Parse outer/parent JSON String
  const rawData = JSON.parse(data);
  //Parse Inner JSON String "Message"
  const messageJson = JSON.parse(rawData.Records[0].Sns.Message);
  //Log value of tinyId to console
  console.log(messageJson.alert.tinyId);
});

相关问题