简体   繁体   中英

How do I get numbers of element from a JSON file with Typescript

  [
     {
       "dataset_id": "courses",
       "dept": "phys",
       "id": "301",
       "avg": 71.67,
       "instructor": "bryman, douglas",
       "title": "elec & magnetism",
       "pass": 146,
       "fail": 6,
       "audit": 0,
       "uuid": 441,
       "year": "2015"
     },
     {
       "dataset_id": "courses",
       "dept": "phys",
       "id": "301",
       "avg": 71.67,
       "instructor": "",
       "title": "elec & magnetism",
       "pass": 146,
       "fail": 6,
       "audit": 0,
       "uuid": 442,
       "year": "2015"
     },
     {
       "dataset_id": "courses",
       "dept": "phys",
       "id": "301",
       "avg": 73.07,
       "instructor": "louis-martinez, domingo",
       "title": "elec & magnetism",
       "pass": 113,
       "fail": 4,
       "audit": 0,
       "uuid": 5957,
       "year": "2013"
     }
   ]

Here is my JSON file and I intend to get a number of elements which is suppose to be 3. I tried to use:

    let num = JSON.parse(file).result.length;

I got a result of Syntax error says "Unexpected token c in JSON at position 0". What did I do wrong?

You'll need to provide a bit more context on how you're getting "file". Is it from an ajax request, is it a static file in your project directory, etc.?

However, since you're using typescript im wagering it is a static file (client or server side shouldnt matter).

You'll probably need to just export it correctly. Add export const variableName = [...] and then you should be able to import it in any file via import file from './filepath' . You shouldnt need to JSON.parse() it.

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