I use a JSON library called JSONObject
(I don\'t mind switching if I need to).
I know how to iterate over JSONArrays
, but when I parse JSO
The simpler approach is (just found on W3Schools):
let data = {.....}; // JSON Object
for(let d in data){
console.log(d); // It gives you property name
console.log(data[d]); // And this gives you its value
}
This approach works fine until you deal with the nested object so this approach will work.
const iterateJSON = (jsonObject, output = {}) => {
for (let d in jsonObject) {
if (typeof jsonObject[d] === "string") {
output[d] = jsonObject[d];
}
if (typeof jsonObject[d] === "object") {
output[d] = iterateJSON(jsonObject[d]);
}
}
return output;
}
And use the method like this
let output = iterateJSON(your_json_object);
I made my small method to log JsonObject fields, and get some stings. See if it can be usefull.
object JsonParser {
val TAG = "JsonParser"
/**
* parse json object
* @param objJson
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?): Map<String, String> {
val map = HashMap<String, String>()
// If obj is a json array
if (objJson is JSONArray) {
for (i in 0 until objJson.length()) {
parseJson(objJson[i])
}
} else if (objJson is JSONObject) {
val it: Iterator<*> = objJson.keys()
while (it.hasNext()) {
val key = it.next().toString()
// If you get an array
when (val jobject = objJson[key]) {
is JSONArray -> {
Log.e(TAG, " JSONArray: $jobject")
parseJson(jobject)
}
is JSONObject -> {
Log.e(TAG, " JSONObject: $jobject")
parseJson(jobject)
}
else -> {
Log.e(TAG, " adding to map: $key $jobject")
map[key] = jobject.toString()
}
}
}
}
return map
}
}
I once had a json that had ids that needed to be incremented by one since they were 0-indexed and that was breaking Mysql auto-increment.
So for each object I wrote this code - might be helpful to someone:
public static void incrementValue(JSONObject obj, List<String> keysToIncrementValue) {
Set<String> keys = obj.keySet();
for (String key : keys) {
Object ob = obj.get(key);
if (keysToIncrementValue.contains(key)) {
obj.put(key, (Integer)obj.get(key) + 1);
}
if (ob instanceof JSONObject) {
incrementValue((JSONObject) ob, keysToIncrementValue);
}
else if (ob instanceof JSONArray) {
JSONArray arr = (JSONArray) ob;
for (int i=0; i < arr.length(); i++) {
Object arrObj = arr.get(0);
if (arrObj instanceof JSONObject) {
incrementValue((JSONObject) arrObj, keysToIncrementValue);
}
}
}
}
}
usage:
JSONObject object = ....
incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
this can be transformed to work for JSONArray as parent object too
org.json.JSONObject now has a keySet() method which returns a Set<String>
and can easily be looped through with a for-each.
for(String key : jsonObject.keySet())
We used below set of code to iterate over JSONObject
fields
Iterator iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
processedJsonObject.add(entry.getKey(), entry.getValue());
}
I will avoid iterator as they can add/remove object during iteration, also for clean code use for loop. it will be simply clean & fewer lines.
Using Java 8 and Lamda [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
jsonObj.keySet().forEach(keyStr ->
{
Object keyvalue = jsonObj.get(keyStr);
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
});
}
Using old way [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
}
}
Original Answer
import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}