1

I wrote a fairly simple scraper in Python that scrapes a JSON string from a server, and outputs it as a table/saves it as a CSV. I am now trying to port my script over to Java but am finding the learning curve a lot steeper.

I have gotten as far as extract my string, but am having trouble recreating the part of my original python script that flattens one of the nested parts of the JSON string.

The element in my JSON string that is nested looks like this:

"workItemProperties":[{"Key":"System.Id","Value":12345},{"Key":"System.Title","Value":"Title text here"},{"Key":"System.IterationPath","Value":"Some\Path\Here"},{"Key":"System.ChangedDate","Value":"\/Date(1555424893503)\/"},{"Key":"System.ChangedBy","Value":"Fred Smith <Fred\Smith>"},{"Key":"Microsoft.VSTS.TCM.AutomationStatus","Value":"Not Automated"}]

In Python the following code would flatten this:

for i in JsonResults['testPoints']:
        for item in i['workItemProperties']:
            key = item['Key']
            i[key] = item['Value']
    del i['workItemProperties']

So that instead of my csv having a single column who's contents is just the nested workItemProperties string, instead System.Id, System.Title, System.IterationPath etc would all be in their own columns.

I am fairly new to coding and struggling to recreate the above in Java, I assume I need loop through the JSONObjects within my JSONArray, but can't seem to get this to work.

Here is the main portion of my code (not including my many failed flattening/un-nesting attempts).

    try {
            document = Jsoup.connect("http://url").userAgent("Opera").proxy("1.2.3.4", 1234).header("Authorization", "Basic " + base64login).timeout(10 * 1000).validateTLSCertificates(false).get();
            Elements jsCode = document.getElementsByClass("__allTestPointsOfSelectedSuite");
            String JsonResults = jsCode.html();
            output = new JSONObject(JsonResults);
            docs = output.getJSONArray("testPoints");
            File file=new File("JSONextract.csv");
                    String csv = CDL.toString(docs);
                 FileUtils.writeStringToFile(file, csv)
            System.out.println(csv);
        } catch (IOException e) {
            e.printStackTrace();
        }

I am currently using the org.json library to read the JSON string.

Current Output: Current Output

Desired Output: enter image description here

4
  • 1
    can you show what output you want? Commented May 8, 2019 at 11:27
  • I have updated my question with screenshots of how my csv currently looks from my java code, and a screenshot of how it looks from my original python script with the contents of workItemProperties being split into columns rather than being nested.
    – Dekks
    Commented May 8, 2019 at 11:41
  • 1
    don't post text as image and if you really think this is good idea then post also plain text as text around your image. Commented May 8, 2019 at 11:42
  • do you need only workitemProperties or all properties of current output except workitemProperties ? Commented May 8, 2019 at 12:09

1 Answer 1

1

Try this ,

If you need only properties of workItemProperties,

docs = output.getJSONArray("testPoints");
JSONArray  properties= new JSONArray();
for(int i = 0; i < docs.size(); i++)
{
      JSONObject object = docs.getJSONObject(i);
      JSONArray  workItemProperties=object.getJSONArray("workItemProperties");
      JSONObject property=new JSONObject();
      for(int j = 0; j < workItemProperties.size(); j++)
         {
      JSONObject temp=workItemProperties.getJSONObject(j);
      property.put(temp.getString("Key"),temp.getString("Value"));
         }
      properties.put(property);
}

File file=new File("JSONextract.csv");
String csv = CDL.toString(properties);
FileUtils.writeStringToFile(file, csv)
System.out.println(csv);

otherwise,

docs = output.getJSONArray("testPoints");
for(int i = 0; i < docs.size(); i++)
{
      JSONObject object = (JSONObject) docs.get(i);
      JSONArray  workItemProperties=object.getJSONArray("workItemProperties");
      for(int j = 0; j < workItemProperties.size(); j++)
         {
      JSONObject property=workItemProperties.getJSONObject(j);
      object.put(property.getString("Key"),property.getString("Value"));
         }
      object.remove("workItemProperties");
}

File file=new File("JSONextract.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv)
System.out.println(csv);
2
  • I get the following error: java:34: error: no suitable method found for put(Object,Object) object.put(property.get("Key"),property.get("Value"));
    – Dekks
    Commented May 8, 2019 at 14:01
  • That absolutely did the job! Thank you! Had to change the second loop to increment J rather than I to stop it infinite looping, but as soon as I did that it worked perfectly. I sort of understand your code but will do some more reading about object.put and property.get (and do more tutorials).
    – Dekks
    Commented May 8, 2019 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.