简体   繁体   English

如何使用CoffeeScript加载和使用静态JSON文件?

[英]How do I load and use a static JSON file using CoffeeScript?

I have gotten some advice to use "requirejs" but am having trouble making it work. 我已经获得一些使用“ requirejs”的建议,但是在使其工作方面遇到了麻烦。 I am a total newbie to CoffeeScript and new to JavaScript as well. 我是CoffeeScript的新手,也是JavaScript的新手。

My JSON file (or more accurately a js file containing a JSON string) looks like this: 我的JSON文件(或更准确地说是包含JSON字符串的js文件)如下所示:

define(function(require)
{
  return 
  {
    "name": "Joe",
    "age": 30
  }
});

My app.coffee has: 我的app.coffee有:

requirejs.config
  paths:
    text: "<path to requirejs-text>"
    json_path: "<path to json file>"

My main.coffee has: 我的main.coffee有:

define(require) ->
  ko = require 'knockout'
  $ = require 'jquery'
  jsonObj = require 'json_path'

  class Main_App
    constructor ->
      @age = ko.observable jsonObj.age

I am getting the following error in my generated JavaScript: 我在生成的JavaScript中遇到以下错误:

Uncaught SyntaxError: Unexpected token : 未捕获到的SyntaxError:意外令牌:

It is complaining about the colon in the line: 它抱怨该行中的冒号:

"name": "Joe", “ name”:“ Joe”,

It seems clear that the javascript wrapper around my JSON string is not structured properly. 显然,围绕我的JSON字符串的javascript包装器结构不正确。 I wanted to read a "data.json" file directly, but it was looking for a ".js" file. 我想直接读取“ data.json”文件,但它正在寻找“ .js”文件。 I was told I needed to wrap the JSON string in a javascript "define(function(require)", but I can't seem to find help on how to format it. Anyone able to get me unstuck? Thanks! 有人告诉我我需要将JSON字符串包装在javascript“ define(function(require)”)中,但我似乎无法找到有关如何设置其格式的帮助。

The Automatic Semicolon Insertion of JavaScript seems to be guilty here. JavaScript的自动分号插入似乎是有罪的。

When you write 当你写

define(function(require)
{
  return // a ; is added here. 
  {
    "name": "Joe",
    "age": 30
  }
});

A semicolon is added behind your back after the return statement, so the function returns undefined instead of your object. 在return语句后的后面加了分号,因此该函数返回undefined而不是您的对象。

Try like this instead : 像这样尝试:

define(function(require)
{
  return {
    "name": "Joe",
    "age": 30
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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