I have a JSONArray which contains multiple JSONObjects
[
{
"record":[
{
"timeStamp":"2018-10-11T05:36:51+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"qwe",
"address":"192.168.1.1",
"type":"A",
"priority":"0",
"ttl":"3600"
},
{
"hostname":"www",
"address":"test.com",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
},
{
"record":[
{
"timeStamp":"2018-10-11T05:36:52+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"rty",
"address":"192.168.1.2",
"type":"A",
"priority":"0",
"ttl":"300"
},
{
"hostname":"*",
"address":"test",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
}
]
How can I parse this JSONArray and export it as a CSV File.
This is what I have tried so far
File file=new File("/home/administrator/Desktop/test.csv");
String csv = jsonArray;
FileUtils.writeStringToFile(file, csv);
System.out.println("CSV created.");
My desired output is
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,300,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
Is it possible to have an output like this given the JSONArray above?
Sorry for the late respond was bashing my keyboard for the past 30 minutes but I finally got it done, here is the code.
public static String getCSVData() throws IOException, JSONException {
Path jsonFile = Paths.get("json");
String json = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(json.trim());
List<List<String>> jsonArrays = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
List<String> jsonObjects = new ArrayList<>();
JSONArray record = jsonArray.getJSONObject(i).getJSONArray("record");
for (int i2 = 0; i2 < record.length(); i2++) {
JSONObject jsonObject = record.getJSONObject(i2);
if (i2 == 0) {
jsonObjects.add(jsonObject.get("timeStamp").toString());
jsonObjects.add(jsonObject.get("code").toString());
jsonObjects.add(jsonObject.get("text").toString());
} else {
jsonObjects.add(jsonObject.get("hostname").toString());
jsonObjects.add(jsonObject.get("address").toString());
jsonObjects.add(jsonObject.get("type").toString());
jsonObjects.add(jsonObject.get("priority").toString());
jsonObjects.add(jsonObject.get("ttl").toString());
}
}
jsonArrays.add(jsonObjects);
}
StringBuilder stringBuilder = new StringBuilder("timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl\n");
for(List<String> arrays : jsonArrays){
stringBuilder.append(StringUtils.join(arrays, ",")).append("\n");
}
return stringBuilder.toString().trim();
}
To explain the code first I looped over the first Array and then get the jsonObject of the first JSONArray and then get the jsonArray named "record" from the JsonObject I have gotten by looping over the first JSONArray and then loop over record and get all the items and save them into an ArrayList. and join them via StringUtils which is provided by JDK.
if you want to write it to file use this
Files.write(Paths.get("YOUR CSV FILE"), getCSVData().getBytes(StandardCharsets.UTF_8));
all the code I used are provided by JDK and org.json.
after we print out getCSVDate(); the output is:
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,3600,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
Related
I am trying to populate a CSV file with json data, but I need to organize everything a certain way. I need the json keys to be headers and the associated values be the data under it, but the way the json is set up I can populate names in one, but the info in another block labeled "items" needs to be split up among multiple cells with keys being the header and the values populating the table. I do not know how to split up individual components of a json block into its own cells.
So CSV should be set up like:
headers: name item1 item2 item3
data cells: [first last] [value1] [value2] [value3]
JSON looks like this:
{
"info":[
{
"name":{
"first" : -----
"last":-----
},
"item": [
{
"item1" : "value1"
"item2" : "value2"
"item3" : "value3"
}
]
}
I have used the Apache commons FileUtils.writeStringToFile, but that writes all the "items" keys and values in one cell, I need 1 item to 1 cell. The name is fine because the components can go in one cell, I just need to split up the items.
The result so far is Name is one header and the cell under that header has first and last name, the second header is Items and lists all keys and values in that json block in that one cell.
I expect the items keys to be the header and the values under those and split up.
Any help or direction would be greatly appreciated.
UPDATE: To clarify I am pulling the JSON data from a URL so the way it is written is the way it is. I can not change it.
public static void main(String[] args) throws IOException {
JSONObject jo = (JSONObject) JSONObject.parse("{\"info\":[{\"name\":{\"first\" : \"-----\",\"last\":\"-----\"},\"item\": [{\"item1\" : \"value1\",\"item2\" : \"value2\",\"item3\" : \"value3\"}]}]}");
String line1 = "headers:\tname\titem1\titem2\titem3\n";
String line2 = "data cells:";
JSONArray info = jo.getJSONArray("info");
JSONObject info1 = info.getJSONObject(0);
JSONObject name = info1.getJSONObject("name");
String nameKeys = name.keySet().toString();
JSONArray item = info1.getJSONArray("item");
JSONObject firstItem = item.getJSONObject(0);
String item1Value = firstItem.getString("item1");
String item2Value = firstItem.getString("item2");
String item3Value = firstItem.getString("item3");
line2 = line2 + "\t" +nameKeys + "\t"+ item1Value +"\t"+item2Value+"\t"+item3Value+"\n";
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\user\\Desktop\\test.csv"));
bw.write(line1);
bw.write(line2);
bw.close();
}
just look like this ,get the value and write them to the csv file.
Another way you can use regex like (?<=item\d"\s:\s").*?(?=") to match the "value1","value2","value3" and regex item\d mathches "item1","item2","item3" to cut out the json string to get the value.
public class JsonToCsv {
public static void main(String args[]) throws JSONException, IOException
{
List<JSONObject> infoList=new ArrayList<JSONObject>();
JSONObject info=new JSONObject();
JSONObject name=new JSONObject();
name.put("first", "John");
name.put("last","Doe");
info.put("name",name );
List<JSONObject> itemList=new ArrayList<JSONObject>();
JSONObject item1=new JSONObject();
JSONObject item2=new JSONObject();
item1.put("item1", "val1");
itemList.add(item1);
item2.put("item2", "val2");
itemList.add(item2);
info.put("item", itemList);
infoList.add(info);
System.out.println(infoList);
convertJsonToCsv(infoList);
}
public static void convertJsonToCsv(List<JSONObject> infoList) throws IOException, JSONException {
FileWriter csvWriter = new FileWriter("InfoFile.csv");
List<String> header= new ArrayList<String>();
List<String> values = new ArrayList<String>();
for(int i=0;i<infoList.size();i++) {
JSONObject info_obj=infoList.get(i);
Iterator<String> info_keys=info_obj.keys();
while(info_keys.hasNext()) {
String key = info_keys.next();
if (info_obj.get(key) instanceof JSONObject) {
JSONObject obj=info_obj.getJSONObject(key);
Iterator<String> obj_keys=obj.keys();
while(obj_keys.hasNext()) {
String k=obj_keys.next();
if(i==0)
header.add(k);
values.add(obj.getString(k));
}
}
if (info_obj.get(key) instanceof JSONArray) {
JSONArray item_array=info_obj.getJSONArray(key);
for(int j=0;j<item_array.length();j++) {
JSONObject item=item_array.getJSONObject(j);
Iterator<String> item_keys=item.keys();
while(item_keys.hasNext()) {
String k=item_keys.next();
if(i==0)
header.add(k);
values.add(item.getString(k));
}
}
}
}
}
for(String head : header) {
csvWriter.append(head);
csvWriter.append(",");
}
csvWriter.append("\n");
for(int m=0;m<values.size();m++) {
csvWriter.append(values.get(m));
if((m+1)%(header.size())==0) {
csvWriter.append("\n");
}
else {
csvWriter.append(",");
}
}
csvWriter.flush();
}
}
I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.
I have a json file like below and want to parse the overlays like overlay1,overlay2,overlay3:
{
"overlays": {
"overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
"sensitivity": 0.6,
},
"overlay2": {
"cgButtonPressedColor": "#ffaa56",
"relative": "screen",
"isOverlayRendered": true,
"cgBorderWidth": "0px",
},
"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}
}
}
Currently I am doing this:
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; i <= 100; i++) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay != null) {
osb.setOverlay(jsp.getOverlay(overlay));
}
}
How can I get the length of overlays (here: overlay1, overlay2, overlay3)? How do I query the length of 3 via the gson API?
And I want to know the overlay1,overlay2,overlay3 in a string or array so that I can iterate over them.
Note: Here I have to iterate 100 times or any times so that I can iterate if overlays increase later in json file. It iterates unnecessarily in looping.
How can I iterate only overlay1 or overlay2 or overlay3 and so without unnecessary iterating?
I mean I just want to get the overlay1, overlay2, overlay3 and so on in jsonobjects via Gson.
I have solved this using this code below.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
Map<String, Object> data = new Gson().fromJson(ovl, type);
Iterator<String> entries = data.keySet().iterator();
while (entries.hasNext())
{ JsonObject overlay = ovl.getAsJsonObject(entries.next().toString());
if (overlay != null)
{
osb.setOverlay(jsp.getOverlay(overlay));
}
}
Have you considered using an array instead of wrapped objects?
{
"overlays": [
{"overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
"sensitivity": 0.6,
}},
{"overlay2": {
"cgButtonPressedColor": "#ffaa56",
"relative": "screen",
"isOverlayRendered": true,
"cgBorderWidth": "0px",
}},
{"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}}
]
}
And using this code:
Gson gson = new Gson();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonArray ovl = job.getAsJsonArray("overlays");
if (ovl != null) {
osb.setOverlay(jsb.getOverlay(ovl.get(ovl.lenght() - 1)));
}
Or if you want to use wrapped json objects, you should create a list and insert elements like this:
Gson gson = new Gson();
List<JsonObject> overlays = new LinkedList<>();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; ; ++i) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay == null) {
break;
} else {
overlays.put(overlay);
}
}
// Use "overlays" list
I need help with parsing a JSON array.
[
{
"Header1": [
{
"path": "upload/images/1430572021716.jpg"
},
{
"path": "upload/images/1430574003703.jpg"
}
]
},
{
"Header2": [
{
"path": "upload/images/1430574124119.jpg"
},
{
"path": "upload/images/1430574203001.jpg"
}
]
}
]
I am receiving the above JSONArray perfectly. I want to iterate through the array and extract both the header text "Header1" and the value of path
I keep running into the following error message
at 0 of type org.json.jsonarray cannot be converted to jsonobject
after some research, this is due to the system not being able to parse to a JSON array. It does work if I change the "list" array to an objct, however this is not an array and i loose the ability to iterate through it.
Here is the code i tried to parse the array with
JSONArray mArray;
mArray = json;
//download json array
for (int i = 0; i < mArray.length(); i++) {
if(mArray != null) {
JSONArray list = mArray.getJSONArray(i);
if(list != null) {
for(int a = 0; a < list.length();a++) {
JSONObject elem = list.getJSONObject(a);
if (elem != null) {
listdata.add(elem.getString("path"));
}
}
}
}
}
You're trying to treat each element of the top-level array as another array - it's not, it's an object. That object then has another field whose value is an array. So you want something like:
for (int i = 0; i < json.length(); i++) {
JSONObject container = json.getJSONObject(i);
// We don't know the property name, but there's only one, apparently...
String key = container.keys().next();
JSONArray subarray = container.getJSONArray(key);
for (int j = 0; j < subarray.length(); j++) {
listdata.add(subarray.getJSONObject(j).getString("path"));
}
}
The second level of your JSON consists in your JSON array elements.
What you need, as you already mention, is to get them as JSONObject.
Then you getJSONArray from that object:
//download json array
for (int i = 0; i < mArray.length(); i++) {
if(mArray != null) {
JSONObject element = mArray.getJSONObject(i);
JSONArray list = element.getJSONArray("Header1");
if(list != null) {
However, since the "Header..." keys are changing, you might need to infer the key by invoking keys().
A much easier way for you to handle this would be to use GSON library and create POJO class to resemble ur JSON here is a nice website to do that
This works for JavaScript and very simple.
//mArray is your json array
let newArray = JSON.stringify(mArray);
mArray = JSON.parse(newArray);
I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling