如何从JSON访问键值?

我从表单中捕获以下信息,数据是json格式(我相信?)

var obj = { "schema":{ "type":"object", "title":"Event Info", "required":[ "name", "emergency_contact_name", "emergency_contact_no", ], "properties":{ "name":{ "type":"string", "minLength":3, "maxLength":10 }, "medical_conditions":{ "title":"Medical Conditions", "type":"string", "maxLength":120 }, "emergency_contact_name":{ "title":"Emergency Contact Name", "type":"string", "maxLength":120 }, "emergency_contact_no":{ "title":"Emergency Contact Number", "type":"string", "maxLength":120 } } } } 

所以我只想获得“必填”字段。 我试过obj ['schema'] ['required']和obj.schema.required,obj ['schema']。obj [0] ['schema'] ['required'],obj [0 ] .schema.required。 这些都不起作用。 如何轻松地检索我想要的属性?

谢谢。

正如你在你的评论中提到的, console.log(typeof obj)打印string ,这意味着你需要将你的string转换为javascript对象。

为此,您必须使用JSON.parse方法。

 obj = JSON.parse(obj); let required = obj['schema']['required'];