How to convert JSON value to escaped String in groovy [JsonSlurper]? - json

i have a groovy script that runs on Jenkins, i have build there a json object using JsonSlurper
The json object is a nested one, i would need to convert the nested json child into escaped string value instead of a json object (that's the requirement :) ).
{"key1":
{"key2":
{"key3":true}
}
}
Into string escaped value:
{"key1": " {\"key2\":{\"key3\":true}} " }
I'm building the json object by using:
def jsont = new JsonSlurper().parseText(row)
doing some manipulation to the json, then need to convert to string:
jsont.key1 = func(jsont.key1) ----> here i want to convert key1 value to escaped string
Any suggestion?

import groovy.json.*
def json = '''{"key1":
{"key2":
{"key3":true}
}
}
'''
def obj = new JsonSlurper().parseText(json)
obj.key1 = JsonOutput.toJson(obj.key1)
json = JsonOutput.toJson(obj)
result:
{"key1":"{\"key2\":{\"key3\":true}}"}

Related

Unable to parse a json string Binary in spark scala

I have a Binary json array string which I need to parse in Spark scala.
This is what I am doing:
import com.github.wnameless.json.flattener.JsonFlattener
def extractBlob(jsonString: String,
defaultValue: String = ""): String = {
JsonFlattener
.flatten(jsonString)
.toString
}
val extractBlobAsText = udf((jS: String) => extractBlob(jS))
val df1 =
df.withColumn("extracted",extractBlobAsText(unhex(col("hex").cast(StringType))))
df1.show(false)
But I am getting this error
com.eclipsesource.json.ParseException: Unexpected end of input at 1:1 at
com.eclipsesource.json.JsonParser.error(JsonParser.java:490) at
com.eclipsesource.json.JsonParser.expected(JsonParser.java:484) at
com.eclipsesource.json.JsonParser.readValue(JsonParser.java:193) at
com.eclipsesource.json.JsonParser.parse(JsonParser.java:152) at
com.eclipsesource.json.JsonParser.parse(JsonParser.java:91) at
com.eclipsesource.json.Json.parse(Json.java:295) at
com.github.wnameless.json.flattener.JsonFlattener.<init>(JsonFlattener.java:144) at
com.github.wnameless.json.flattener.JsonFlattener.flatten(JsonFlattener.java:100) at
notebook0.Cell5$285.extractBlob(Cell5:12) at
Also, I do not know the JSON schema. All I know is that it is a Json array. So I also need to do explode later.

Groovy: JSON Parsing

Seeing an interesting issue, not sure this is to do with parser or the way it suppose to parse. Any help is appreciated
import groovy.json.JsonSlurper
def dMatch = '''[{"match":{"keyId":"A-102161-application"}},{"match":{"keyId":"A-102162-application"}},{"match":{"keyId":"A-102163-application"}},{"match":{"keyId":"A-102164-application"}},{"match":{"keyId":"A-102165-application"}}]'''
println "T1:: List: " + dMatch
def parser = new JsonSlurper()
def exclude = parser.parseText(dMatch)
println "T2:: Obj: " + exclude.toString()
println "----------------------------------------------------"
Output :
T1:: List: [{"match":{"keyId":"A-102161-application"}},
{"match":{"keyId":"A-102162-application"}},
{"match":{"keyId":"A-102163-application"}},
{"match":{"keyId":"A-102164-application"}},
{"match":{"keyId":"A-102165-application"}}]
T2:: Obj: *[[match:[keyId:A-102161-application]],
[match:[keyId:A-102162-application]],
[match:[keyId:A-102163-application]],
[match:[keyId:A-102164-application]],
[match:[keyId:A-102165-application]]]*
The parsed object supposed to be same as the string but all the values were converted as array list of map.
Any idea why this is generating object like this ? When this is sent to camunda it complains
org.camunda.bpm.engine.ProcessEngineException: Cannot serialize object in variable 'exclude': groovy.json.internal.LazyMap
Use JsonSlurperClassic() - it produces standard HashMap that is serializable.
And if you want to convert object back to json use Json output.toJson(obj)

How to convert following string to JSON in python

How can i convert the below string to JSON using python?
str1 = "{'a':'1', 'b':'2'}"
The json library in python has a function loads which enables you to convert a string (in JSON format) into a JSON. Following code for your reference:
import json
str1 = '{"a":"1", "b":"2"}'
data = json.loads(str1)
print(data)
Note: You have to use ' for enclosing the string, whereas " for the objects and its values.
The string in OP's question is not JSON because the keys and values are enclosed by single-quotes. The function ast.literal_eval can be used to parse this string into a Python dictionary.
import ast
str1 = "{'a':'1', 'b':'2'}"
d = ast.literal_eval(str1)
d["a"] # output is "1"
Other answers like https://stackoverflow.com/a/58540688/5666087 and https://stackoverflow.com/a/58540879/5666087 were able to use the json library because they changed str1 from "{'a':'1', 'b':'2'}" to '{"a":"1", "b":"2"}'. The former is invalid JSON, whereas the latter is valid JSON.
import json
str1 = '{"a":"1", "b":"2"}'
jsonData = json.loads(str1)
print(jsonData["a"])
Reference : LINK

Groovy script json response length

I need to find json response length. Sample response looks like below:
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
As two parameters are present in resource. So, i should have got response as 2.
Please let me know hoe i can find json length as 2
This is the working solution, try this
import groovy.json.JsonSlurper // import this class
def jsonText = '''{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}'''
def json = new JsonSlurper().parseText(jsonText)
println "Json length---------->"+json.resource.size()
If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following,
println jsonObject.resource.size() // Here resource is the key(sub node) inside your json
If you want to get the length of parent JSON key, just do as follows,
println jsonObject.size()
Based on your question, it appears that you would like to know the count of properties within a JSON object. So we can do that by following these steps:
STEP 1 : Parse the response string into JSON object
STEP 2 : Convert JSON object into groovy Map object
Step 3 : Call size() method on Map object to get the elements count within the map object
So your code would like this :
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')
def object = (Map)response.resource
log.info object.size()
So your output will be 2. You can try adding more elements to JSON object check if it works.
Hope this helps :)

Convert scala json string to an object

I need to convert a string json in an object using scala.
I tried this, but I cannot access the prop Name, for example
import scala.util.parsing.json._
val parsed = JSON.parseFull("""{"Name":"abc", "age":10}""")
How can I do to get an string json and convert to an object? Thanks
val parsed = JSON.parseFull("""{"Name":"abc", "age":10}""")
val parsed = JSON.parseFull(parsed)
try it