Home > Enterprise >  How can I extract data from a JSON file using javascript?
How can I extract data from a JSON file using javascript?

Time:12-16

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!

CodePudding user response:

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);

CodePudding user response:

Use the JavaScript function JSON.stringify().

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

const y = JSON.stringify(x);
JSON.parse(y);
console.log(y.status);
  • Related