I want to extract all these places mentioned in "location" field and does not want the other fields in the below json.but can't be able to extract since it is nested..Can anyone help me?
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
System.out.println("data::"+curNext.get("list.myList.location");
}
My "curNext" gives output as::
{
"_id": {
"$oid": "51ebe983e4b0d529b4df2a0e"
},
"date": {
"$date": "2013-07-21T13:31:11.000Z"
},
"lTitle": "Three held for running CISF job racket",
"list": {
"myList": [
{
"location": "Germany"
},
{
"location": "Geneva"
},
{
"location": "Paris"
}
]
},
"hash": -1535814113,
"category": "news"
}
I want my output as
Germany,Geneva,Paris
I have been in a long wait here for an answer and finally I got what I was searching for...Just noting my answer so someone else can benefit from it
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
String res=curNext.toString();
JsonElement jelement = new JsonParser().parse(res);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("list");
JsonArray jarray = jobject.getAsJsonArray("myList");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("location").getAsString();
System.out.println("all places::"+result);
}
For finding only locations you should used mongo aggregation, below query will fetch all lcoations array
db.collectionName.aggregate({
"$unwind": "$ner.nerList"
},
{
"$group": {
"_id": "$_id",
"location": {
"$push": "$ner.nerList.location"
}
}
},
{
"$project": {
"location": "$location",
"_id": 0
}
})
Unfortunately I don't know how to convert this in Java but, I find below links which helpfull to you for converting above query in java format
Mongo Java aggregation driver
Related
I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.
This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.
1.
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
The JSON the ID I need to access has a comment next to it:
"data": [
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"$state": "save",
"$process_flow": false,
"Street": "95## ### ######",
"id": "**3461487000073355176**", ----This is the ID I need -----
"Coverage_A_Dwelling": 100000,
"$approval": {
"delegate": false,
"approve": false,
"reject": false,
"resubmit": false
},
"Created_Time": "2020-12-10T09:05:17-05:00",
"Property_Details": "Primary Residence",
"Created_By": {
"name": "My name",
"id": "346148700000017",
"email": "m#gmail.com"
},
"Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
"$review_process": {
"approve": false,
"reject": false,
"resubmit": false
},
"Property_State": "FL",
"Property_Street": "95",
"Roof_Material": "Asphalt Shingle",
"Full_Name": "Clare Em",
"Property_City": "Land ",
"Email_Opt_Out": false,
"Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
"Insured_1_DOB": "1942-02-20",
"$orchestration": false,
"Tag": [],
"Email": "cr#yahoo.com",
"$currency_symbol": "$",
"$converted": false,
"Zip_Code": "338",
"$approved": true,
"$editable": true,
"City": "Land O Lakes",
"State": "FL",
"Structure_Type": "Single Family",
"Prior_Carrier": {
"name": "Default Carrier (DO NOT DELETE OR CHANGE)",
"id": "3461487000000235093"
},
"Source": {
"name": "EverQ",
"id": "346148700006474"
},
"First_Name": "Clarence",
"Modified_By": {
"name": "My name",
"id": "3461487000000172021",
"email": "m#gmail.com"
},
"Phone": "7036159075",
"Modified_Time": "2020-12-10T09:05:17-05:00",
"$converted_detail": {},
"Last_Name": "####",
"$in_merge": false,
"$approval_state": "approved",
"Property_Zip": "34638"
}
],
"info": {
"per_page": 200,
"count": 1,
"page": 1,
"more_records": false
}
}
If I understood it correctly, you can get the id like this:
Here, json has the following value.
[
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"id": "**3461487000073355176**"
...
}
]
Now I can iterate over JSONArray to get the id.
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String id = (String) jsonObject.get("id");
System.out.println(id);
}
It prints out **3461487000073355176**.
You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.
The posted JSON response is missing the initial "{".
Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):
// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?
For example, defining something like this:
#Getter #Setter
// This models the response string from body
public class Response {
#Getter #Setter
// This models objects in the data list/array
public static class IdHolder {
// Only id because not interested of the rest
private String id;
}
// Only list of id holders because not interested of the rest
private List<IdHolder> data;
}
Then it would be as easy as:
Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);
Json1:
{
"array1": [
{
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Street": "st.road",
"pin": "789723"
}
},
{
"Name": "XYZ Company",
"Address": {
"Street": "Peters road",
"pin": "789700"
}
}
]
}
Json2:
{
"array2":[
{
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Street": "st.road",
"pin": "789723"
}
},
{
"Name": "XYZ Company",
"Description": "Domestic Cleaning Supply Company",
"Address": {
"Street": "Peters road",
"pin": "789700"
}
}
]
}
Java Code used by me:
JsonParser Parser = new JsonParser();
Object obj1 = Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON1.json"));
Object obj2 = Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON2.json"));
JsonObject jsonObject1 = (JsonObject) obj1;
JsonObject jsonObject2 = (JsonObject) obj2;
Set<Map.Entry<String, JsonElement>> entries1 = jsonObject1.entrySet();
Set<Map.Entry<String, JsonElement>> entries2 = jsonObject2.entrySet();
for (Map.Entry<String, JsonElement> entry : entries1) {
//System.out.println("FirstJson:"+entry.getKey());
}
for (Map.Entry<String, JsonElement> entry : entries2) {
//System.out.println("SecondJson:"+entry.getKey());
}
if (jsonObject1.equals(jsonObject2)) {
System.out.println("Success");
} else {
entries1.removeAll(entries2);
//System.out.println("\n");
System.out.println("Result:" + entries1);
}
I have to compare two json files which contain arrays using Java, In array1 "Description" is missing I have to print that exact key and not the entire Json from first to last. In my output also "Description" is not there, but it's not printing exactly that key, its printing from first to last. Please help me with this.
The output I got:
Result:[array1=[{"Name":"Xytrex Co.","Description":"Industrial Cleaning Supply Company","Account Number":"ABC15797531","Address":{"Street":"st.road","pin":"789723"}},{"Name":"XYZ Company","Address":{"Street":"Peters road","pin":"789700"}}]]
This library is clean way to handle json comparison. It also has compare mode like strict check etc.
http://jsonassert.skyscreamer.org/javadoc/org/skyscreamer/jsonassert/JSONCompare.html
For your usecase you can check JSONCompareResult solves your problem.
I'd suggest you to use https://github.com/eBay/json-comparison library.
This library based on JsonAssert project but provide additional features
such as 'Exclude paths' , dealing with order and more
Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}
I have this JSON I need to parse. Its format looks something likes this:
{
"47M": [
{
"lat": 39.95507,
"lng": -75.152122,
"label": 8011,
"VehicleID": 8011,
"BlockID": 7995,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 1,
"Offset_sec": 29
},
{
"lat": 39.913765,
"lng": -75.155464,
"label": 8038,
"VehicleID": 8038,
"BlockID": 7993,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 3,
"Offset_sec": 158
}
]
}
However, that "47M" can be "5", "H", "101", etc. And I need to get those "5", "H", etc.
I believe I should use the loop for (obj : root) , but I don't know what's the type for obj
You could use simple json (https://code.google.com/p/json-simple/) Library and code like this to iterate over the keys.
JSONParser parser = new JSONParser();
jObject = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) jObject;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
my json data is like bellow:
"scores": [
{
"type": "exam",
"score": 1
},
{
"type": "quiz",
"score": 2
},
{
"type": "homework",
"score": 3
},
{
"type": "homework",
"score": 4
}
]
I'm using below code to retrieve only score.
while(cursor.hasNext())
{
BasicDBObject acc=( BasicDBObject) cursor.next();
acc.get("scores");
for(int i=0;i<=acc.size();i++)
{
((BSONObject) acc.get(i)).containsField("score");
}
//System.out.println(acc);
}
I'm getting null point exception. What is wrong?
This is what you will have to do:
while(cursor.hasNext())
{
BasicDBObject acc=(BasicDBObject) cursor.next();
BasicDBList scores = (BasicDBList) acc.get("scores");
for(int i=0;i<scores.size();i++)
{
BasicDBObject score = (BasicDBObject) scores.get(i);
System.out.println(score.get("score"));
}
}
Few notes:
You need to loop the scores array (I assume it's array) and not the BasicDBObject itself. Hence you need to cast it to BasicDBList. Otherwise you will have to defend against Cast Exceptions
Java arrays elements are from 0...size()-1. So use < and not <= in your loop.