简体   繁体   中英

How to use local JSON assets to simulate API in Scala.js

I'm new to Scala and Scala.js and I want to experiment with handling JSON data. I'd like to simulate a server response by returning the content of a JSON file local to my Scala.js project, parse it and work with the data . What would be the best way to do so? Where should I place these files in my project tree, and how would I get their content?

Say that I have a file called myJSON.json containing something like

[
  {
    "ress": "AR",
    "lastDate": "2017-10-27 09:19:18"
  },
  {
    "ress": "JIM",
    "lastDate": "2017-10-27 06:57:15"
  },
  {
    "ress": "JOE",
    "lastDate": "2017-09-29 11:57:39"
  }
]

Can I place this file somewhere in my project so that I can read this file and then parse its content to use it somehow (could be displayed in the browser, logged to the console, etc...)? I guess I could use a tool such as scala-js or something similar for parsing, but accessing the file content in the first place is what I try to figure out .

Note that I'm using scala-js.

Thanks in advance!

Like others said above, Javascript that runs in the browser in general can't access the local filesystem. There are some exceptions:

  • The File API lets you access files that the user has selected in the UI using <input type="file" /> or drag-and-dropped into the browser window.

  • The Filesystem API lets you access files the way you seem to want, but it is non-standard and is not supported in most browsers. It also seems that Scala.js has no typings for it, but I'm not sure.

scala-js-dom has typings for the File API that you can use – search for File and FileList types in its source. Its API mirrors the Javascript API, so you will need to look for how exactly to do this in JS. Then translating it into Scala.js will be easy (or at least a different question).

If the File API does not work for your use case, another option is to use something like json-server to easily serve your JSON files on localhost via HTTP.

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