How to create existing JSON in groovy, using JsonBuilder? - json

I'm looking for definition (structure) of object that can be converted to following JSON
{
"header":{
"callbackUrl":"",
"clientOrderId":"A565132",
"clientOriginationId":"2345FE",
"serviceProvider":"VERIZON",
"transactionId":"EEDT44567"
},
"customer": {
"nationalIdType":"",
"nationalId":"",
"addresses":[
{
"type":"WORK",
"postalCode":"330066"
}
],
"serviceProviderAuthentication":[
{
"passcode":"",
"securityQuestion":"",
"securityAnswer":""
}
]
},
"accountPhoneNumber":"",
"accountNumber":""
}

If you're looking for an example of how JsonBuilder would be used to create the JSON you've given, here it is
def json = new groovy.json.JsonBuilder()
json header: [
callbackUrl:"",
clientOrderId:"A565132",
clientOriginationId:"2345FE",
serviceProvider:"VERIZON",
transactionId:"EEDT44567"
],
customer:[
nationalIdType:"",
nationalId:"",
addresses: [
[
type:"WORK",
postalCode:"330066"
]
],
serviceProviderAuthentication:[
[
passcode:"",
securityQuestion:"",
securityAnswer:""
]
]
],
accountPhoneNumber:"",
accountNumber:""
json.toString()
You might have been confused about how to create a JSON that doesn't have a root. The answer is: by passing a map.

Related

How to select JSON array (JSON substring) in JasperReport with JSONQL?

I want to create a report using Jaspersoft Studio with a json file as datasource. I want to select some fields from this json and also a substring of the original json. This should be done by jsonql.
First, an example with the "JSON language" in JasperSoftStudio:
gives the following result:
This is exactly what I want to have, the delivery note number as a field, and the barcodes as an array of objects / json substring.
What I am not able to do is, to achieve this with jsonql. The following query
gives the result
The following json was used for this example
{
"tour": {
"shipments": [
{
"containers": [
{
"boxes": [
{
"customerModule": "DEFG",
"deliveryDateTime": "2022-04-25 11:49:24.834000",
"boxNumber": 2
},
{
"customerModule": "ABCD",
"deliveryDateTime": "2022-04-25 11:50:24.810000",
"boxNumber": 1
}
],
"licensePlate": "123"
}
],
"deliveryNoteNumber": "6785000",
"barcodes": [
{
"content": "barcode_01_04"
},
{
"content": "barcode_03_04"
},
{
"content": "barcode_04_04"
}
]
},
{
"containers": [
{
"boxes": [
{
"customerModule": "ZXYV",
"deliveryDateTime": "2022-04-25 11:51:24.834000",
"boxNumber": 1
},
{
"customerModule": "UHGI",
"deliveryDateTime": "2022-04-25 11:52:24.834000",
"boxNumber": 2
}
],
"licensePlate": "987"
}
],
"deliveryNoteNumber": "6785001",
"barcodes": [
{
"content": "Barcode_01_04"
},
{
"content": "Barcode_02_04"
},
{
"content": "Barcode_04_04"
}
]
}
],
"handlingDateTime": "2022-04-25 11:50:24.883000"
}
I tried to use this documentation, but I could not get it working.
The JSONQL data source doesn't properly convert arrays to Strings for some reason.
What you can do is change the barcodes field from java.lang.String to java.lang.Object. You can do that by clicking Edit in the Fields tab and changing the Class Type for the field.
With java.lang.Object as field type, the field value will be the underlying JSON (Jackson) model array object. You can do $F{barcodes}.toString() if you need to explicitly convert it to a String in an expression.

Convert array of JSON objects to string in pyspark

I have one requirement in which I need to create a custom JSON from the columns returned from one PySpark dataframe. So I wrote one UDF like the below which will return a JSON in String format from UDF for each row.
Parameter "entities" are in the array of JSON format.
def halResponse(entities, admantx, copilot_id):
json_resp = "{\"analyzedContent\": {"+json.dumps(entities)+"}}"
return json_resp
But in the response, I am not getting proper JSON i.e instead of proper key: value pair, I am just getting values(actual values replace with * for security purpose), not key and value.
Find the sample response:
"analyzedContents": [
{
"entities": [
[
"******",
*,
*********,
[
[
"***********",
"***********",
"***********",
[
"*****************"
],
**********
]
],
"**************"
]
]
}
]
}
Please help me to resolve this issue. After fixing, I should get the below sample response
"analyzedContents": [
{
"entities": [
[
"key":******",
"key":*,
"key":*********,
[
[
"key":"***********",
"key":"***********",
"key":"***********",
[
"key":"*****************"
],
"key":**********
]
],
"key":"**************"
]
]
}
]
}
Try this without using an UDF:
import pyspark.sql.functions as F
df2 = df.withColumn(
'response',
F.concat(
F.lit("{\"analyzedContent\": {"),
F.to_json(F.col("entities")),
F.lit("}}")
)
)

API POST request in Julia

I am trying to convert some Python code to Julia. Here is the Python code:
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
json = {
"query": [
{
"code": "Kon",
"selection": {
"filter": "item",
"values": [
"1",
"2"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"000000LV"
]
}
}
],
"response": {
"format": "px"
}
}
r = requests.post(url=url, json=json)
Below is the Julia code, that is not working, with this error message:
syntax: { } vector syntax is discontinued around path:8
top-level scope at population_data.jl:8
using DataFrames, DataFramesMeta, HTTP, JSON3
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
json = {
"query": [
{
"code": "Kon",
"selection": {
"filter": "item",
"values": [
"1",
"2",
"1+2"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"000000LV"
]
}
}
],
"response": {
"format": "px"
}
}
r = HTTP.post(url, json)
My attempts to solve this are the following:
Convert the json variable to a string using """ around it.
Converting the JSON string to Julia data types, using JSON3.read()
Passing the converted JSON string to the POST request. This gives the following error:
IOError(Base.IOError("read: connection reset by peer (ECONNRESET)", -54) during request(http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749)
None of it works, and I am not even sure that it is about the JSON format. It could be that I am passing the wrong parameters to the POST request. What should I do?
One way of solving this consists in building the parameters as native julia data structures, and use JSON to convert and use them as the body of your PUT request:
Dictionaries in julia are built using a syntax like Dict(key => value). Arrays are built using a standard syntax: [a, b, c]. The julia native data structure equivalent to your parameters would look like this:
params = Dict(
"query" => [
Dict("code" => "Kon",
"selection" => Dict(
"filter" => "item",
"values" => [
"1",
"2",
"1+2"
]),
),
Dict("code"=> "ContentsCode",
"selection" => Dict(
"filter" => "item",
"values" => [
"000000LV"
]),
),
],
"response" => Dict(
"format" => "px"
))
Then, you can use JSON.json() to build the JSON representation of it as a string and pass it to the HTTP request:
using HTTP
using JSON
url = "http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101G/BefUtvKon1749"
# send the request
r = HTTP.request("POST", url,
["Content-Type" => "application/json"],
JSON.json(params))
# retrieve the response body as a string
b = String(r.body)

Flatten JSON array of objects that contain an array with Jolt

I'm using Jolt 0.1.0, and trying to transform the following JSON:
{
"records": [
{
"collectionId": "COLLECTION1",
"recordIds": [
"recA",
"recB"
]
},
{
"collectionId": "COLLECTION1",
"recordIds": [
"recC",
"recD",
"recE"
]
},
{
"collectionId": "COLLECTION2",
"recordIds": [
"recF",
"recG"
]
}
]
}
... to this:
{
"records": [
"COLLECTION1:recA",
"COLLECTION1:recB",
"COLLECTION1:recC",
"COLLECTION1:recD",
"COLLECTION1:recE",
"COLLECTION2:recF",
"COLLECTION2:recG"
]
}
I've made several attempts with the modify-default-beta operator and the concat function, but can't seem to make it work.
Very similar to https://github.com/bazaarvoice/jolt/issues/656 which required 4 steps.

render as JSON clipping of the zeros of the floating point value

I have a map which is like this, which has to be rendered as JSON to the output.
def formatedResult = [
results:[
[ Name:foo, sex:m, salary:171.900 ],
[ Name:bar, sex:m, salary:171.900 ]
]
]
I am rendering this response as
withFormat {
json {
render formatedResult as JSON
}
}
which produces the following result.
{
results: [{
Name: "foo",
sex: "m",
salary: 171.9
}, {
Name: "bar",
sex: "m",
salary: 171.9
}]
}
But is clipping off the zeros from the salary. What should I do to get the JSON with out clipping off the zeros?
If you are hard coding your values as in your example put them like this:
def formatedResult = [
results:[
[ Name:foo, sex:m, salary:"171.900" ],
[ Name:bar, sex:m, salary:"171.900" ]
]
]
Or if you are getting them from variable use toString() method to convert them to string.
def formatedResult = [
results:[
[ Name:foo, sex:m, salary:salary.toString()],
[ Name:bar, sex:m, salary:salary.toString()]
]
]
Finally your render:
withFormat {
json {
render formatedResult as JSON
}
}