I have a Json object like this in my Postgres DB:
{
"emails": [
{
"email": {
"id": "e8dc927f-679d-496b-85fb-465edf35c676",
"value": "hello#gmail.com"
}
},
{
"email": {
"id": "1b78758a-abc4-46ef-9de9-c999a0c8c418",
"value": "hello1#gmail.com"
}
}
],
"lastName": {
"id": "718109fd-2d00-475a-829a-c8af9a7f0067",
"value": "lastName"
},
"firstName": {
"id": "6c46a5b3-6f89-4692-a214-4943de22018d",
"value": "firstName"
},
}
And so on big json with around 1000 elements, now I want to parse and get the first 500 elements from json and make another json. what I mean by element here is anything which has Id is a element. For example firstName , LastName, email, email are the elements not the emails. I tried Jackson api but couldn't find a way how to count the elements and make a json exactly like above and return. and when I do any modifications in the first 500 elements I should save the Json with edits. Any help is much appreciated. I even tried postgres array_agg(e) function but that is only accepting only array.
I want to convert jsonobjcts into csv files. Wy (working) attempt so far is to load the json file as a JSONObject (from the googlecode.josn-simple library), then converting them with jsonPath into a string array which is then used to build the csv rows. However I am facing a problem with jsonPath. From the given example json...
{
"issues": [
{
"key": "abc",
"fields": {
"issuetype": {
"name": "Bug",
"id": "1",
"subtask": false
},
"priority": {
"name": "Major",
"id": "3"
},
"created": "2020-5-11",
"status": {
"name": "OPEN"
}
}
},
{
"key": "def",
"fields": {
"issuetype": {
"name": "Info",
"id": "5",
"subtask": false
},
"priority": {
"name": "Minor",
"id": "2"
},
"created": "2020-5-8",
"status": {
"name": "DONE"
}
}
}
]}
I want to select the following:
[
"abc",
"Bug",
"Major",
"2020-5-11",
"OPEN",
"def",
"Info",
"Minor",
"2020-5-8",
"DONE"
]
The csv should look like that:
abc,Bug,Major,2020-5-11,OPEN
def,Info,Minor,2020-5-8,DONE
I tried $.issues.[*].[key,fields] and I get
"abc",
{
"issuetype": {
"name": "Bug",
"id": "1",
"subtask": false
},
"priority": {
"name": "Major",
"id": "3"
},
"created": "2020-5-11",
"status": {
"name": "OPEN"
}
},
"def",
{
"issuetype": {
"name": "Info",
"id": "5",
"subtask": false
},
"priority": {
"name": "Minor",
"id": "2"
},
"created": "2020-5-8",
"status": {
"name": "DONE"
}
}
]
But when I want to select e.g. only "created" $.issues.[*].[key,fields.[created]
[
"2020-5-11",
"2020-5-8"
]
This is the result.
But I just do not get how to select "key" and e.g. "name" in the field issuetype.
How do I do that with jsonPath or is there a better way to filter a jsonfile and then convert it into a csv?
I recommend what I believe is a better way - which is to create a set of Java classes which represent the structure of your JSON data. When you read the JSON into these classes, you can manipulate the data using standard Java.
I also recommend a different JSON parser - in this case Jackson, but there are others. Why? Mainly, familiarity - see later on for more notes on that.
Starting with the end result: Assuming I have a class called Container which contains all the issues listed in the JSON file, I can then populate it with the following:
//import com.fasterxml.jackson.databind.ObjectMapper;
String jsonString = "{...}" // your JSON data as a string, for this demo.
ObjectMapper objectMapper = new ObjectMapper();
Container container = objectMapper.readValue(jsonString, Container.class);
Now I can print out all the issues in the CSV format you want as follows:
container.getIssues().forEach((issue) -> {
printCsvRow(issue);
});
Here, the printCsvRow() method looks like this:
private void printCsvRow(Issue issue) {
String key = issue.getKey();
Fields fields = issue.getFields();
String type = fields.getIssuetype().getName();
String priority = fields.getPriority().getName();
String created = fields.getCreated();
String status = fields.getStatus().getName();
System.out.println(String.join(",", key, type, priority, created, status));
}
In reality, I would use a CSV library to ensure records are formatted correctly - the above is just for illustration, to show how the JSON data can be accessed.
The following is printed:
abc,Bug,Major,2020-5-11,OPEN
def,Info,Minor,2020-5-8,DONE
And to filter only OPEN records, I can do something like this:
container.getIssues()
.stream()
.filter(issue -> issue.getFields().getStatus().getName().equals("OPEN"))
.forEach((issue) -> {
printCsvRow(issue);
});
The following is printed:
abc,Bug,Major,2020-5-11,OPEN
To enable Jackson, I use Maven with the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
In case you don't use Maven, this gives me 3 JARs: jackson-databind, jackson-annotations, and jackson-core.
To create the nested Java classes I need (to mirror the structure of the JSON), I use a tool which generates them for me using your sample JSON.
In my case, I used this tool, but there are others.
I chose "Container" as the name of the root Java class; a source type of JSON; and selected Jackson 2.x annotations. I also requested getters and setters.
I added the generated classes (Fields, Issue, Issuetype, Priority, Status, and Container) to my project.
WARNING: The completeness of these Java classes is only as good as the sample JSON. But you can, of course, enhance these classes to more accurately reflect the actual JSON you need to handle.
The Jackson ObjectMapper takes care of loading the JSON into the class structure.
I chose to use Jackson instead of JsonPath, simply because of familiarity. JsonPath appears to have very similar object mapping capabilities - but I have never used those features of JsonPath.
Final note: You can use xpath style predicates in JsonPath to access individual data items and groups of items - as you describe in your question. But (in my experience) it is almost always worth the extra effort to create Java classes, if you want to process all your data in more flexible ways - especially if that involves transforming the JSON input into different output structures.
I have a request of the following JSON format:
{
"profile": {
"created": 1505202655,
"createdBy": "abc",
"updated": 1505202655,
"updatedBy": "xyz"
},
"likesId": [
"0010127916"
],
"icon": null,
"Attributes": {
"backgroundColor": "#FFFFFF",
"logo": "images/Logos/P0010127916.jpg",
"textColor": "#000000"
},
"profileId": "PACYG0010916",
"restrictions": {
"clients": [
"Android",
"SmartTv"
],
"UserTypes": [
"user1",
"user2"
],
"periodEnd": 1512978849,
"periodStart": 1505202849
},
}
I am trying to save the above JSON request Object in the dynamoDb table using putItem. However I am stuck in some issues which are as follows:
Can I store this whole JSON request as-is(without escaping double quotes) in the form of item in dynamodb table?
In case of likesId and Attributes I am storing them as a List and Map with the help of .withList and .withMap methods respectively, but in case of profile I have taken it as a POJO which has 4 states, how can I save this object with the putItem as I did not find any method for saving objects like this, as we have methods for string, numbers and other datatypes, how can I save my own object?
Any kind of guidance will be highly appreciated as I am new to dynamoDb and learning it by doing POC.
You should be able to save it quite easily with the DocumentClient class:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
var params = {
TableName : 'Table',
Item: item
};
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
Where item is the object from your original question
i have json like
{
"condition": "AND",
"rules": [{
"id": "BirthDate",
"field": "BirthDate",
"type": "date",
"input": "text",
"operator": "equal",
"value": "2016/04/13"
}]}
i just want to iterate it on servlet for that i create
public String getRuleList(){
String ruleList=this.get("rules");
return ruleList;
}
public String getcondition(){
return this.get("condition");
}
as getter setter when i send this json without using JSON.stringify i got the value of condition but unable to fetch rules.By using JSON.stringify i unable to fetch anything. please help..
rules is JSONArray and simple get returns an object. Try to get it with the json libraries custom method.
If you are using org.json try this
this.getJSONArray('rules')
Try to provide some more information such as the json library you are using, the output you got for this.get('rules') and how is this initialized for a much better answer
To solve above problem i do
result =JSON.stringify(result);
var json = JSON.parse(result);
var queryData={
rules:JSON.stringify(json.rules),
condition:JSON.stringify(json.condition)
};
console.log("result"+JSON.stringify(result));
if (!$.isEmptyObject(result)) {
var url = location.protocol + "//" + location.host +appContext+"?command=QueryBuilderServlet&action=getQueryJson";
$.ajax({
url:url,
type: "POST",
data:queryData,
dataType:'json',
});
thanks a lot for your help
I am using fusion chart in my application.I am taking json array from servlet to javascript.
Code :
var customerCountList=response.sharecountlist;
FusionCharts.ready(function(){
var revenueChart = new FusionCharts({
type: "column3d",
renderAt: "spraybookerCount-bar",
width: "500",
height: "300",
dataFormat: "json",
dataSource: {
"chart": {
"caption": "Revenue for last year",
"palettecolors": "e44a00",
"subCaption": "Harry's SuperMart",
"xAxisName": "refvalue",
"yAxisName": "['viewcount']",
"theme": "carbon"
},
"data"://here i want to use response.sharecountlist
}
});
revenueChart.render("spraybookerCount-bar");
});
here sharecountlist is sharecountlist==[{"viewcount":99,"refvalue":"Guest"},{"viewcount":4,"refvalue":"facebook"},{"viewcount":2,"refvalue":"friend"}].
sharecountlist is dynamic ,so how can I use this sharecountlist in place of data in above code. Please help me.
Thanks.