存取巢狀結果中的動態JSON 鍵
在JSON 資料中,鍵可以是動態的,這表示它們因對象而異。這在存取特定值時可能會帶來挑戰,尤其是在嵌套結構中。
要處理巢狀結果中的動態 JSON 鍵,您可以利用 JSONObject 類別中的 keys() 方法。此方法傳回迭代器,讓您迭代 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" } ] }
存取「question_mark」欄位的內容對於「search_result」陣列中的每個對象,您可以使用以下程式碼:
for (JSONObject searchResult : searchResults) { JSONObject questionMark = searchResult.getJSONObject("question_mark"); Iterator<String> keys = questionMark.keys(); while (keys.hasNext()) { String currentDynamicKey = keys.next(); // Get the value of the dynamic key JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // Do something here with the value... } }
此程式碼迭代「question_mark」欄位中的可用鍵並檢索與每個鍵關聯的值。然後,您可以使用這些值進行進一步處理或顯示。
以上是如何存取巢狀結果中的動態 JSON 鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!