将本地JSON文件加载到变量中 [英] Load local JSON file into variable

查看:659
本文介绍了将本地JSON文件加载到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将.json文件加载到javascript中的变量中,但我无法让它工作。它可能只是一个小错误,但我找不到它。

I'm trying to load a .json file into a variable in javascript, but I can't get it to work. It's probably just a minor error but I can't find it.

当我使用这样的静态数据时,一切正常:

Everything works just fine when I use static data like this:

var json = {
            id: "whatever", 
            name: "start",
            children: [{
                         "id":"0.9685","name":" contents:queue"},{
                         "id":"0.79281","name":" contents:mqq_error"}}]
        }

所以我将{}中的所有内容放在content.json文件中并尝试将其加载到本地javascript变量,如下所述:将json加载到变量

So I put everything that's in {} in a content.json file and tried to load that into a local javascript variable like explained here: load json into variable

var json = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "/content.json",
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();

我用chrome调试器运行它,它总是告诉我变量json的值为null 。 content.json与调用它的.js文件驻留在同一目录中。

I ran it with the chrome debugger and it always tells me that the value of the variable json is null. The content.json resides in the same directory as the .js file that is calling it.

我错过了什么?

推荐答案

如果您直接将对象粘贴到content.json中,则它是无效的json。除非值为数字,否则json键AND值必须用双引号(不是单引号)包装。以下将是您的对象作为有效的json。

If you pasted your object into content.json directly, it is invalid json. json keys AND values must be wrapped in double quotes (not single!) unless the value is numeric. Below would be your object as valid json.

{
  "id": "whatever", 
  "name": "start",
  "children": [{
    "id":"0.9685","name":" contents:queue"},{
    "id":"0.79281","name":" contents:mqq_error"}]
}

(你还有一个额外的}

这篇关于将本地JSON文件加载到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆