-1

I have a JSON file which contains the following:

[
  {
    “name”: “Joshia \”Placement\” Fonz”,
    “color”: “white”
  },
  {
    "name": “Trin Brin”,
    “color”: “black”
  },
  {
    “name”: “Su Et”,
    “color”: “yellow”
  }
]

And I would like to parse it to use the array and objects for the application. So './students.json' being the path for the JSON file, I attempted JSON.parse('./students.json') but got an error Uncaught SyntaxError: Unexpected token . in JSON at position 0, and tried JSON.stringify('./students.json') but it simply returned me the exact string of the path './students.json'.

So can I parse the JSON file in Javascript to use the array?

Thank you

Seki
  • 11,135
  • 7
  • 46
  • 70

3 Answers3

1

You should use an ajax request for that, jQuery ($) provides an abstraction for XHR.

$.get("./students.json", function(data){
   //success callback
   // data is the json you requested already parsed
}, "json");

Is the fastest way to achieve your goal, as long as by default client side is not able to read a file from the server even if there are file API for client-side file reading but I guess that in this case it may provide you more problems than it actually solve.

File

FileReader

steo
  • 4,586
  • 2
  • 33
  • 64
  • I'm not making any requests. I just have a file called `students.json` and trying to use the array. –  Oct 30 '16 at 19:36
  • And to retrieve that file you need to make a request. The client side won't magically retrieve it through a path. – steo Oct 31 '16 at 10:26
1

That's because you are parsing the string './students.json' not what is inside the file. You should open the file and then take the info. You could use this example to read the file https://stackoverflow.com/a/14446538/5334265 . Then use JSON.parse to the content.

Community
  • 1
  • 1
Shil Nevado
  • 716
  • 1
  • 11
  • 30
  • I'm not making any requests. I already have the file called `students.json` and I want to parse it to use the array. How can I do that? –  Oct 30 '16 at 19:38
  • 1
    but you need a request to your own server to get the file. Like the example of @steo – Shil Nevado Oct 30 '16 at 20:36
0

JSON is a leagal javascript so you can just add to your page:

<script language="JavaScript" type="text/javascript" src="./students.json"></script>
O_Z
  • 1,515
  • 9
  • 11