Parsing internal JSON file in JSONArray in Java using org.json - java

I would like to be able to parse a JSON file that is structured something like:
[
{
"id": 1,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
},
{
"id": 2,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
}
etc...
]
into something looking like
array(
[0] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
[1] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
etc...
)
I'm pretty sure i have an idea on how to convert it into the format I want, but im having trouble actually reading the data from the file.
The two major issues im having:
Reading it from inside the jar.
Most of the examples used json.simple, and the json library i'm using doesn't seem to have that.
I tried some examples online, and a couple of the answers on this post
but no luck the biggest issue is that all of them are giving examples for reading an external file, while I'm trying to read one that is packaged inside the jar.
My project tree:
MyProject
L src
L myPackage
L MyClass.java
L MyJsonFile.json
The closest thing that I'm guessing almost worked is this (from the link above):
import org.json.JSONArray;
//code
JSONArray myJSONArray = new JSONArray(Main.class.getResourceAsStream("myFile.json"));
But that only seems to throw an error:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
Thanks in advance!

The problem is org.json.JSONArray will only accept String,Collection or Array but you are trying to pass the InputStream object. which is what error messages also says
org.json.JSONException: JSONArray initial value should be a string or collection or array
So first convert the InputStream into String
InputStream inputStream = Main.class.getResourceAsStream("myFile.json");
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
And then convert it into JSONArray
JSONArray myJSONArray = new JSONArray(sb.toString());
After here you can iterate the JSONArray using for loop, like here

Related

Issue in parsing a BufferedReader object

I need to read the output of a BufferedReader object which is in json format, parse the json and extract some values. My code looks as below:
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc1.getInputStream()));
Stream<String> s = reader.lines();
Object[] t = s.toArray();
String result = Arrays.toString(t);
JSONParser jp = new JSONParser();
JSONArray jArr = (JSONArray) jp.parse(result);
System.out.println(jArr);
The JSONArray jArr looks as below:
[
{
"result": {
"totalSize": 1,
"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
],
"done": true
},
"status": 0
}
]
I need to get the properties of "records". I have the subsequent code working, just need to create a json object with the values inside "records". Output json object required is:
{"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
I am facing json array and json object incompatibility issues while trying to case jArr as json object. Can someone suggest a way to do this
Join the stream as a single String. Use try-with-resources so the BufferedReader gets closed.
String result;
try (Stream<String> stream = reader.lines()) {
result = stream.collect(Collectors.joining());
}

How to import json array into java program using JSON.ORG

I am learning to work with json files and I'm using the JSON-java library from https://github.com/stleary/JSON-java
I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
You are almost there, all you have to do is to new a JSON array from jsonToken as follows:
BTW, I think the JSON library you are using is org.json, not JSON.ORG. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}

Java : JSONObject.put looped gives wrong order?

Today I started writing a simple parser for a log file. I want to take the log file and transform it into a simple json structure.
The log file is consistent and has 3 main parts (example below):
the timestamp [23 digits]
the code [4 digits]
the payload [variable digits]
Example log
2018-07-25T08:47:16,094,164f,test1
2018-07-25T08:47:18,163,1678,test2
2018-07-25T08:47:19,501,1662,test3
2018-07-25T08:47:21,278,1634,test4
2018-07-25T08:47:23,347,1632,test5
2018-07-25T08:47:24,686,1665,test6
2018-07-25T08:47:26,463,1678,test7
2018-07-25T08:47:28,533,1678,test8
2018-07-25T08:47:29,877,1632,test9
2018-07-25T08:47:31,687,1632,test10
From this I wanted to create a JSON file that would incorporate well the information inside. This is what I came up with (using org.json.JSONObject library).
BufferedReader reader = new BufferedReader(new FileReader ("file.log"));
String line = null;
String timestamp = null;
String eventCode = null;
String payload = null;
JSONObject codePayload = new JSONObject();
JSONObject finalString = new JSONObject();
for (int i = 0; i < 10; i++) {
line = reader.readLine();
timestamp = line.substring(0, 23);
eventCode = line.substring(24, 28);
payload = line.substring(29, line.length());
codePayload.put("ID", eventCode);
codePayload.put("PL", payload);
finalString.put(timestamp, codePayload);
codePayload = new JSONObject();
}
System.out.println(finalString.toString());
This little snippet should work quite well (don't mind the for) and it kinda does. It creates the JSON file according to the string I give it but it puts then in a strange order, see below.
{
"2018-07-25T08:47:24,686": {
"ID": "1665",
"PL": "test6"
},
"2018-07-25T08:47:29,877": {
"ID": "1632",
"PL": "test9"
},
"2018-07-25T08:47:31,687": {
"ID": "1632",
"PL": "test10"
},
"2018-07-25T08:47:16,094": {
"ID": "164f",
"PL": "test1"
},
"2018-07-25T08:47:21,278": {
"ID": "1634",
"PL": "test4"
},
"2018-07-25T08:47:18,163": {
"ID": "1678",
"PL": "test2"
},
"2018-07-25T08:47:23,347": {
"ID": "1632",
"PL": "test5"
},
"2018-07-25T08:47:28,533": {
"ID": "1678",
"PL": "test8"
},
"2018-07-25T08:47:19,501": {
"ID": "1662",
"PL": "test3"
},
"2018-07-25T08:47:26,463": {
"ID": "1678",
"PL": "test7"
}
}
As you can clearly see it places the objects in the wrong order and I really don't know why. If someone has the slightest idea on how this problem could occur please comment below. Thanks a lot!
The org.json.JSONObject is un-ordered, so better to use javax.json.JSONObject OR if you are using org.json library, use the org.json.JSONArray to store the timestamps in order.

updating json value of a nested json array in a json file | Java

I have this below json content in a file.
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
I am able to parse this file and then traverse this json to get to the node where i wish to update. Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem.
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
I have just the json reader till this point so do I construct a String as-and-when I traverse the nodes and when i reach the point I need to update, I update it (and construct the remainder of the nodes in this json object, (not to break from the loop)) and then write the entire reconstructed string to same file? Or is there a better approach where I can traverse the JSONObject and once i update it, push the entire object onto a file without constructing a String of entire file.
I still need to figure out a way to take either of the approach. So any pointers or direction will be greatly helpful.

read json file and parse inner json array in java

{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));

Categories