解析嵌套JSON 結果中的動態JSON 鍵
問題:
如何訪問JSON 結果中動態值的鍵的內容?
範例JSON:
{ "status": "OK", "search_result": [ { "product": "abc", "id": "1132", "question_mark": { "141": { "count": "141", "more_description": "this is abc", "seq": "2" }, "8911": { "count": "8911", "more_desc": "this is cup", "seq": "1" } }, "name": "some name", "description": "This is some product" }, { "product": "XYZ", "id": "1129", "question_mark": { "379": { "count": "379", "more_desc": "this is xyz", "seq": "5" }, "845": { "count": "845", "more_desc": "this is table", "seq": "6" }, "12383": { "count": "12383", "more_desc": "Jumbo", "seq": "4" }, "257258": { "count": "257258", "more_desc": "large", "seq": "1" } }, "name": "some other name", "description": "this is some other product" } ] }
解:
要存取巢狀鍵,請使用JSONObject 類別的keys() 方法。此方法傳回一個迭代器,可用於迭代物件中的鍵。取得金鑰後,您可以使用 getJSONObject(key) 方法檢索對應的值。
以下範例展示如何解析範例 JSON 中的動態金鑰:
JSONObject searchResult = ...; // Assuming searchResult is a JSONObject JSONObject questionMark = searchResult.getJSONObject("question_mark"); Iterator keys = questionMark.keys(); while (keys.hasNext()) { String currentDynamicKey = (String) keys.next(); JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // Do something with the dynamic key and value... }
此程式碼迭代 Question_mark 物件中的鍵並擷取對應的值。然後您可以使用這些值來存取您需要的資料。
以上是如何存取嵌套 JSON 結果中的動態鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!