2010-12-16 6 views
0

javascriptを使って簡単なJSONを評価することができます。Javascriptを使用して内部レイヤーを持つJSONを解析する方法は?

var json = '{"amount":"50","id":"3"}'; 
var out = eval("{" + json + "}"); 

は今、私はそう単純ではevalが機能しないインナーJSONを持つ JSONを行い、テーブル名が含まれるであろうRESTとJSON-nizedクエリ結果でJPAを使用しています。

{"inventory":{"amount":"50","id":"3"}} 

私は解決策についてウェブを見回しましたが、私のケースを見つけることができません。 文字列操作を行い、{"amount":"50","id":"3"}部分を抽出するだけですか? 他の方法がありますか?

答えて

3

はい、別の(より良い)方法があります。ので、この上記は、まだ動作json2.jsが含まれ、古いブラウザ(例えばIE < 8)については

var obj = JSON.parse(jsonString); 
//then, for example... 
var amount = obj.inventory.amount; 

をネイティブJSONサポートなし:あなたのJSONを解析し、あなたのオブジェクトを取得するにはJSON.parse()を使用してください。

+0

ありがとうございます!それは完璧な解決策です:D –

1

でも、これは動作するはずです:

var json = '{"inventory":{"amount":"50","id":"3"}}'; 
var out = eval("{" + json + "}"); 

alert(out.inventory.amount); 

しかし、より良いがJSON.parse

0

Aniwayを使用するために、私はシンプルにevalを実行するための適切な方法は、JSON文字列は、括弧で囲まれているように、カーリーはないと思われますブラケット...

var out = eval( "(" + "json +") ");

Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js

// In the third stage we use the eval function to compile the text into a 
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity 
// in JavaScript: it can begin a block or an object literal. We wrap the text 
// in parens to eliminate the ambiguity. 

       j = eval('(' + text + ')');