NodeJS JavaScript将txt转换为JSON,无法获取JSON数据,返回undefined

vcirk6k6  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(101)

首先将txt转换为JSON。

const txt = JSON.stringify(`{
  ErrorList: [{ 80: 'Prepared' }],
  Reference: [
    {
      'Rule Name': 'Missing 3',
      'Rule ID': 1,
      'Rule Des': 'Did they provide News ?'
    },
    {
      'Rule Name': 'Missing Zip',
      'Rule ID': 2,
      'Rule Des': 'Is field ?'
    }
  ],
  'Hard Violation': [
    {
      Violation: 0,
      'Initial Servicer': 'BI',
      'Total Confirmed': 0,
      'Last Date': '05/16/2021'
    },
    {
      Violation: 0,
      'Initial Servicer': 'BI',
      'Total Confirmed': 3,
      'Last Date': '12/19/2019'
    }
  ]
}`);

const obj = JSON.parse(txt);
console.log(obj.Reference);

然后,我试图得到一些值的JSON,我试图打印“引用”里面,但它返回“未定义”,任何朋友可以帮助?

a5g8bdjr

a5g8bdjr1#

谢谢你的回复,特别是@ T. J.克劳德
对我来说,最好的方法是创建一个对象,直接执行:

const obj = { ErrorList: [ { 80: "Prepared", /*...*/ } ] /*...*/ };
pobjuy32

pobjuy322#

you have to do like this

const text = `{

    "ErrorList": [
        {
            "80": "Prepared"
        }
    ],
    "Reference": [
        {
            "Rule Name": "Missing 3",
            "Rule ID": 1,
            "Rule Des": "Did they provide News ?"
        },
        {
            "Rule Name": "Missing Zip",
            "Rule ID": 2,
            "Rule Des": "Is field ?"
        }
    ],
    "Hard Violation": [
        {
            "Violation": 0,
            "Initial Servicer": "BI",
            "Total Confirmed": 0,
            "Last Date": "05/16/2021"
        },
        {
            "Violation": 0,
            "Initial Servicer": "BI",
            "Total Confirmed": 3,
            "Last Date": "12/19/2019"
        }
    ]
}`;

// Parse the JSON string into a JavaScript object
const jsonObj = JSON.parse(text);

// Access and manipulate the object as needed

console.log(jsonO`enter code here`bj.ErrorList);
console.log(jsonObj.Reference);
console.log(jsonObj['Hard Violation']);

相关问题