简体   繁体   中英

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

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM