JSでJSONデータがあるかどうかを判断する方法


伝えられたJSONデータの中に、あるフィールドが存在するかどうかをどう判断しますか?
1.obj[key]!=undefined
このような欠陥があって、もしこのkeyが定義されていて、しかも非常に2の割当値がundefinedであるなら、この文は問題になります。
2.!("key"in obj)
3.obj.hasOwnProperty(「key」)
この二つの方法がいいです。オススメです。
答え:
Actualy,checking for undefined-ness is not an accurate way of testing whether a key exists.What if the key exists but the value is actually undefined?
var obj={key:undefined}
obj[key]undefined/false、but the key exists!
You shound instead use the in operator:
“key”in obj//true,regardless of the actual value
If you want to check if a key doesn't exist,remember to use parenthesis:
!("key「in obj」//true if」key「doesn't exist in object」
!”key"in obj//ERROR!Equivalent to「false in obj」
Or,if you want to particularly test for properties of the object instance(and not inherity properties)、usehas OwnProperty:
Obj.hasOwn Property(「key」)//true
PS:Json操作については、ここでいくつかの実用的なjsonオンラインツールを紹介します。
オンラインJSONコード検査、検査、美化、フォーマットツール:
http://tools.jb51.net/code/json
JSONオンラインフォーマットツール:
http://tools.jb51.net/code/jsonformat
オンラインXML/JSON相互変換ツール:
http://tools.jb51.net/code/xmljson
jsonコードはオンラインフォーマット/美化/圧縮/編集/変換ツール:
http://tools.jb51.net/code/jsoncodeformat
オンラインJson圧縮/変換ツール:
http://tools.jb51.net/code/json_yasuo_トラッキング
C言語スタイル/HTML/CSS/Jsonコードフォーマット美化ツール:
http://tools.jb51.net/code/ccode_同前css_Json