2

jQueryでJSONファイルを読み込もうとしています:

       var listOfItems;
       $(function() {
            $.getJSON('myData.json', function(data) {
                listOfItems = data.items;
            });
        });

これはmyData.jsonです:

{
    {"source": "Microsoft", "target": "Amazon", "type": "licensing"},
    {"source": "Microsoft", "target": "HTC", "type": "licensing"},
    {"source": "Samsung", "target": "Apple", "type": "suit"},
    {"source": "Motorola", "target": "Apple", "type": "suit"}
}

listOfItemsただし、Chrome Web Developerは、このコードの後に​​は未定義であると述べています。なんで?javascript、HTML、JSONファイルの両方が同じディレクトリにあると確信しています。

4

5 に答える 5

2

JSONを修正します。jsonlintは何が悪いのかを教えてくれます。

JSONのプロパティ名は文字列であるため(識別子である可能性のあるJavaScriptとは異なり)、引用符で囲む必要があります。

于 2012-04-06T19:55:05.977 に答える
1

ここでの主な問題は、含まれている配列に「[」の代わりに「{」を使用することです

あなたが持っている必要があります

[
    {source: "Microsoft", target: "Amazon", type: "licensing"},
    {source: "Microsoft", target: "HTC", type: "licensing"},
    {source: "Samsung", target: "Apple", type: "suit"},
    {source: "Motorola", target: "Apple", type: "suit"},
]
于 2012-04-06T19:59:09.283 に答える
1

あなたmyData.jsonは有効なJSONではありません。

オブジェクトが含まれているように見えますが、オブジェクト自体には4つのオブジェクトが含まれていますが、これらの内部オブジェクトにはプロパティ名が付けられていません。

これは有効です

{
    "one"   : { "source":  "Microsoft", "target" : "Amazon", "type" : "licensing" },
    "two"   : { "source" : "Microsoft", "target" : "HTC",    "type" : "licensing" },
    "three" : { "source" : "Samsung",   "target" : "Apple",  "type" : "suit" },
    "four"  : { "source" : "Motorola",  "target" : "Apple",  "type" : "suit" }
}

しかし、あなたlistOfItemsを考えると、私はそれがあなたが望むものではないと思います。おそらくオブジェクトの配列が必要です。

これは、中括弧の代わりに角括弧を使用して行われます

[
    { "source":  "Microsoft", "target" : "Amazon", "type" : "licensing" },
    { "source" : "Microsoft", "target" : "HTC",    "type" : "licensing" },
    { "source" : "Samsung",   "target" : "Apple",  "type" : "suit" },
    { "source" : "Motorola",  "target" : "Apple",  "type" : "suit" }
]

また、最後の項目の末尾のコンマに注意してください。一部のブラウザ/JavaScriptエンジンでは機能しません。JSONパーサーがそれを許可するかどうかはわかりません。

于 2012-04-06T20:00:23.920 に答える
1

これは非同期イベントです。非同期イベントでは、そのような変数の割り当てを実行することはできません。その特定の関数内で実行している操作を実行する必要があります。それ以外の場合は、同期イベントであることを確認してください(JQueryで正しい変数を設定することにより)。このイベントは、操作(この場合はGETリクエストの完了)を待ってからコードを続行します(これはお勧めしません)。

于 2012-04-07T11:04:48.200 に答える
0

jQuery.parseJSON();を使用してjsonを解析できます。

http://api.jquery.com/jQuery.parseJSON/

不正な形式のJSON文字列を渡すと、例外がスローされる可能性があります。たとえば、以下はすべて不正な形式のJSON文字列です。

{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).

さらに、何も渡さない場合、空の文字列、null、または未定義の場合、'null'がparseJSONから返されます。ブラウザがJSON.parseのネイティブ実装を提供する場合、jQueryはそれを使用して文字列を解析します。JSON形式の詳細については、http://json.org/を参照してください。

于 2012-04-06T19:57:44.957 に答える