Reputation: 2970
I'm using org.json
to lookup json objects and values (org.json
is a requirement), and I'm trying to reach the child array elements.
My json:
{
"Info": {
"name": "my_json",
},
"my_array": {
"arrays": [
{
"array 1": [
{
"name": "red",
"server": "red1",
"capacity": "123"
},
{
"name": "blue",
"server": "blue1",
"capacity": "456"
}
]
},
{
"array 2": [
{
"name": "white",
"server": "white1",
"capacity": "1234"
},
{
"name": "black",
"server": "black1",
"capacity": "4567"
}
]
}
]
}
}
This outputs:
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
The method looks like:
public static String processJson(String[] args) throws JSONException {
String value = "";
String jsonData = readFile(args[0]);
JSONObject jobj = new JSONObject(jsonData);
if (args[1].equals("my_array")) {
JSONObject parent = jobj.getJSONObject("my_array");
JSONArray jarr = parent.getJSONArray("arrays");
for (int i = 0; i < jarr.length(); i++) {
for (int j = 0; j < jarr.length(); j++) {
JSONObject test1 = jarr.getJSONObject(j);
System.out.println(test1);
}
}
}
return value;
}
I would like the return value to be:
[{"name":"red","capacity":"123","server":"red1"
{"capacity":"456","name":"blue","name":"blue1"}]
Is it possible to get array 1
elements?
I thought the nested loop will take care of it, but it only outputs the same time.
Upvotes: 1
Views: 1197
Reputation: 44834
If you only want the first element then you don't need a loop
JSONObject test1 = jarr.getJSONObject(0);
System.out.println(test1);
If you want to format test1
your can
System.out.println (test1.toString ().replace ("{\"array 1\":", ""));
Upvotes: 2