0

I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.

const x = `{
        "status": "ok",
        "userTier": "developer",
        "total": 2314500,
        "startIndex": 1,
        "pageSize": 10,
        "currentPage": 1,
        "pages": 231450,
        "orderBy": "newest"
            }`;

JSON.parse(x);
console.log(x.status);

Can anybody suggest something I may be doing wrong? Thank you!

1 Answers1

2

JSON.parse Return value The Object, Array, string, number, boolean, or null value corresponding to the given JSON text. - MDN

You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:

const x = `{
        "status": "ok",
        "userTier": "developer",
        "total": 2314500,
        "startIndex": 1,
        "pageSize": 10,
        "currentPage": 1,
        "pages": 231450,
        "orderBy": "newest"
            }`;

const parsedData = JSON.parse(x);
console.log(parsedData.status);

or you can directly get value one time after parsed as:

const x = `{
        "status": "ok",
        "userTier": "developer",
        "total": 2314500,
        "startIndex": 1,
        "pageSize": 10,
        "currentPage": 1,
        "pages": 231450,
        "orderBy": "newest"
            }`;

console.log(JSON.parse(x).status);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • This is the answer. @PythonProgrammer Use this. – HoldOffHunger Dec 16 '21 at 01:24
  • 1
    Sorry, I've actually tried that already. I still get the same result of "undefined". I've run the data through jsonlint exactly as its retrieved by my xmlrequest to verify it is json format. Would it be better if I posted my code in its entirety? – PythonProgrammer Dec 16 '21 at 01:27