JSONLD: How to convert a json into JsonLD? - java

I have a use case where I have a Json data and I have to convert that into JSONLD format.
First Question : Can this be done easily , like some API for this, that probably I am missing ?
Second Question : If not then what are the steps that needs to be taken.
So the Json Looks like :
{
key:"language",
value: "scala"
}
And I want to convert it into the JSONLD format.
Any help is appreciated.

You can simply add a context on this json object like :
{
#context: {
"key": "http://schema.org/description",
"value": "http://schema.org/value"
},
key: "language",
value: "scala"
}

If you are interested in using JavaScript library to do this task, then npm module JSONLD is great one.
Note: This library has dependency on PYTHON.
JavaScript code Example from JSONLD site:
var doc = {
"http://schema.org/name": "Manu Sporny",
"http://schema.org/url": {"#id": "http://manu.sporny.org/"},
"http://schema.org/image": {"#id": "http://manu.sporny.org/images/manu.png"}
};
var context = {
"name": "http://schema.org/name",
"homepage": {"#id": "http://schema.org/url", "#type": "#id"},
"image": {"#id": "http://schema.org/image", "#type": "#id"}
};
// compact a document according to a particular context
// see: http://json-ld.org/spec/latest/json-ld/#compacted-document-form
jsonld.compact(doc, context, function(err, compacted) {
console.log(JSON.stringify(compacted, null, 2));
});
Output:
{
"#context": {...},
"name": "Manu Sporny",
"homepage": "http://manu.sporny.org/",
"image": "http://manu.sporny.org/images/manu.png"
}
When I was searching for JavaScript library for the JSON to JSONLD transformation, I could come up with this one. But, as this library has PYTHON dependency, I am searching for other JavaScript library for the same.

Related

After REST API call ,i have key/value pair in the below format ,I Need to extract just the specific value corresponding to the key

Option 1 :if i use the TALEND job i get the JSON results stored with backslashes in the JSON file for some reason(which is unparseable)
{"read":[{"Body":"{\"items\":[{\"executionId\":\"a0613a31-d16d-4c4d-9279-4564a86cdd44\",\"startTimestamp\":\"2021-09-15T22:30:26.854Z\",\"triggerTimestamp\":\"2021-09-15T22:30:27.209Z\",\"userId\":\"user1\",\"status\":\"dispatching\",\"runtime{\"type\":\"REMOTE_ENGINE_CLUSTER\"},\"executionStatus\":\"DISPATCHING_FLOW\"},{\"executionId\":\"49a56eb1-f3c7-4f26-9554-8fa88acde38b\",\"startTimestamp\":\"2021-09-15T22:29:15.999Z\",\"triggerTimestamp\":\"2021-09-15T22:29:16.447Z\",\"userId\":\"user1\",\"executionType\":\"MANUAL\",\"status\":\"dispatching\",\"runtime\":{\"type\":\"REMOTE_ENGINE_CLUSTER\"},\"executionStatus\":\"DISPATCHING_FLOW\"}],\"limit\":100,\"offset\":0,\"total\":2}","ERROR_CODE":null}]}
Option 2:Using the WEB URL:
After REST API call,i have the JSON results like:
BODY:context.statusbody
{
"items": [{
"executionId": "4f679c12-d8d7-4dd7-89d5-507a94503988",
"startTimestamp": "2021-09-14T19:05:01.854Z",
"triggerTimestamp": "2021-09-14T19:05:02.385Z",
"userId": "user1",
"taskId": "60b7f6d31c6e394de0163d35",
"status": "dispatching",
"runtime": {
"type": "REMOTE_ENGINE_CLUSTER"
},
"executionStatus": "DISPATCHING_FLOW"
},
{
"executionId": "4f40b04c-1ac1-42ea-9a36-7c25b1b17fe8",
"startTimestamp": "2021-09-14T19:00:24.769Z",
"triggerTimestamp": "2021-09-14T19:00:25.122Z",
"userId": "user1",
"taskId": "60b7f6d31c6e394de0163d35",
"executionType": "SCHEDULED",
"status": "dispatching",
"runtime": {
"type": "REMOTE_ENGINE_CLUSTER"
},
"executionStatus": "DISPATCHING_FLOW"
}
],
"limit": 100,
"offset": 0,
"total": 2
}
From this i just need to extract the executionID and triggerTimestamp for each iteration and store in a global variable
In my grayed out tjava3 i am using global variable as:
context.testexecutionID=((String)globalMap.get("executionID"));
context.triggerTimestamp=((String)globalMap.get("triggerTimestamp"));
context.executionID=context.testexecutionID.substring(5, context.testexecutionID.lastIndexOf("\"")-3);
context.triggerTime=context.triggerTimestamp.substring(5, context.triggerTimestamp.lastIndexOf("\"")-3);
#sarah Based on your valid JSON you added in your edit .
i suggest you to add after tRest to add tExtractJSONFields component paremetred as such :
Job Design should be in first test :
tRest -> tExtractJSONFields -> tLogRow .
If extraction is good . Second test you have to see my previous my first answer to get global Variables .
Okey , Json i Used for your case to do your requirement :
Note That your Json is not Valid
{
"items": [{
"executionId": "6e5fa777-9ede-42b9-b862-03b4b1b12375",
"startTimestamp": "2021-09-15T05:59:40.599Z",
"triggerTimestamp": "2021-09-15T05:59:41.006Z",
"userId": "user"
}],
"limit ": 100,
"offset ": 0,
"total ": 2
}
Without knowing your job design i just got the output that is posted right here .
My job design is as such :
Important !: your tFileInputJson should be like this to get the 2 fields
Same configuration if your want to used tExtractJSONFields .
to Stock your Global Variables :
to get the globalVariables easy way is to use tfixedFlowInput :
Output :

Read hateoas response with embedded HAL collection with spring

I'm trying to read a REST HATEOAS response like this one :
{
"_embedded": {
"tasks": [
{
"id": 1,
"name":"task1"
"_links": {
"self": {
"href": "http://localhost:8080/v1/tasks/1"
},
"tasks": {
"href": "http://localhost:8080/v1/tasks"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/v1/tasks?page=0&size=1"
}
},
"page": {
"size": 1,
"totalElements": 1,
"totalPages": 1,
"number": 0
}
}
I'm trying to folloaw the example of spring's documentation : spring hateoas traverson.
Java code :
...
TypeReferences.ResourcesType<Resources<Task>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resources<Task>>(){};
Traverson traverson = new Traverson(new URI("http://localhost:8080/v1/tasks"), MediaTypes.HAL_JSON);
Traverson.TraversalBuilder builder = traverson.follow(rel("tasks")).withHeaders(headers);
Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
...
But I obtain this error :
Did not find LinkDiscoverer supporting media type text/html!
Cause : "follow(rel("tasks"))" don't find "tasks".
I'm trying other solutions like this one :
Deserialize JSON containing (_links and _embedded) using spring-hateoas, I obtain the error "Expected to find link with rel ..." too.
Maybe finaly I'm not understand the good manner to use traverson object.
I solve my problem by parsing myself the response in Json, but are they another way to get the list contains in the "_embedded" tags in a list of beans ?
If you have some examples I'm interesting :).
I think you need to use a Json Path expression to access the embedded content.
Traverson.TraversalBuilder builder = traverson.follow("$._embedded.tasks[0]").withHeaders(headers);
Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
The following tool is useful for playing with the path expression: http://www.jsonquerytool.com/
BTW, your JSON is missing a "," after the "name".

Json Transformation in java with high performance

I need to transform a Json into another Json according to the parameter coming as part of Rest request. This service is developed in Java. I know, Jackson API can be used easily and there are some libraries also available. But my requirement is to delivery response with new Json faster as much as possible.
If I can be given few option I can measure the performance of those.
Let's assume I have this Json in data storage:
{
"bookId": "23228232-2dfa232",
"bookName": "Json Transformation",
"bookPublisher": "Tech Publication",
"bookRating": [
{
"source": "All book rank",
"maxRating": "10",
"rating": "3.4"
},
{
"source": "Tech Books",
"maxRating": "5",
"rating": "2"
},
{
"source": "Popular",
"maxRating": "3",
"rating": "1"
}
],
"bookAuthor": [
{
"name": "Jone",
"specialities": [
"Json",
"Javascript",
"Typescript",
"nodejs"
]
},
{
"name": "Mike",
"specialities": [
"Java",
"Spring",
"ElasticSearch"
]
}
]
}
Below rest calls should have respective results from this Json:
Get only authors
/authorName/23228232-2dfa232
{
authorName: [
"Jone",
"Mike"
]
}
Get Average Rating
/popularity/23228232-2dfa232
{
rating: "1.78"
}
So, the question is how to do this kind of transformation efficiently with any available library? As I mentioned above, I can simply use any Json library in Java and transform the Json, but I am not sure, if that will be efficient.
You can try little json java library for searching json data.
JsonValue json = JsonParser.parse(stringvariablewithjsondata);
List<JsonValue> authors = json.findAll(SPM.path("bookAuthor", "name")));
List<String> ratings = json.findAllLiterals(SPM.path("bookRating", "rating")));
and compute result like
JsonArray values = JsonFactory.array();
for(JsonValue value : authors) values.add(value);
JsonObject result = JsonFactory.object().add("authorName", values);
return result.toCompactString()
You can use JSON-Java --> https://www.baeldung.com/java-org-json
Or the Google JSON, aka GSON and a few others as listed here --> https://javarevisited.blogspot.com/2016/09/top-5-json-library-in-java-JEE.html
To see popularity and use statistics, which might help you chose which ones to test first: https://www.baeldung.com/java-json
You can use GSON as it easily maps JSON with POJO classes (Especially nested ones)
For a quick reference for performance comparison,

Is there a way to dynamically set variables values for the post request with jmeter beanshell preprocessor

I need to dynamically build the following post request JSON body with jmeter beanshell preprocessor. I am referring to the following question which has a solution for my problem with looped strings. I would need to do this with json-property(variables) an array of JSON objects with different name and values. Thanks a lot.
{
"processDefinitionId":"optaplannerkey:1:dbc4af8f-7e04-11e9-afa3-1ecac26bb5e0",
"businessKey":"optaplannerkey",
"returnVariables":true,
"variables": [
{
"name": "TaskDescription",
"value": "Fixing the issue with sink"
},
{
"name": "TaskCategory",
"value": "plumbing"
},
{
"name": "Priority",
"value": "Medium"
},
{
"name": "Status",
"value": "New"
},
{
"name": "SkillsRequired",
"value": "Plumbing Skills"
},
{
"name": "DueDate",
"value": "2019-05-24T11:23:08.030+05:30"
}
]
}
Use dummy sampler with the parameterized json request and CSV Data Set Config for the dynamic input. Below, I have paremeterized only two for demo.
Then, Use JSR223 Post processor with the following code:-
vars.put("responseVar",prev.getResponseDataAsString());
This will put response body in "responseVar" variable. Fetch it using ${responseVar}
Hope this helps.

How to escape HTML in JSON

I'm wondering how can I escape HTML code in JSON ? I'm using Jackson as my JSON mapper.
In my content I have various characters: tags, single quotes, double quotes, new lines character (\n), tabs etc. I tried to use CharacterEscapes class, but with no results.
My JSON response blows up after using CharacterEscapes. I tried to escape it manually, but also without any results.
So the question is, lets say that we have:
<p>Some text</p>\n<p>"SomeText"</p>
How can I send it back to browser as value of the JSON object?
UPDATE:
Input is:
{
"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part": "1",
"cont": true
},
"html": "<p>Mine text</p>"
}
Output:
{
"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part":"1",
"cont": true
},
"html":{"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part":"
}
For now I have found following solution:
I have added CharacterEscapes to the JsonFactory of the ObjectMapper class.
Also I have changed way of writting JSON into response.
Instead of
objectMapper.writeValue(response.getWriter(), myObject)
I'm doing this:
PrintWriter writer = response.getWriter();
writer.print(String.valueOf(objectMapper.writeValueAsBytes(myObject));
writer.flush();
And it works as I wanted.
I would suggest to use either of below.
1.You can use GSON library for this purpose.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
2.Use Apache commons StringEscapeUtils.escapeHtml("JSON string").

Categories

Resources