How to send a json script as a file to groovy - json

Below is my JSON script.
PRAMS.json
{
"JSON" : {
"test": "iTEST",
"testname": "BOV-VDSL-link-Rateprofile-CLI-Test-1",
"params": [
{
"n2x_variables / config_file": "C:/Program Files (x86)/Agilent/N2X/RouterTester900/UserData/config/7.30 EA SP1 Release/OSP Regression/BOV/Bov-data-1-single-rate-profile.xml"
},
{
"n2x_variables / port_list": "303/4 303/1"
}
]
}
}
Below is my groovy script and I am sending params.json script to the same groovy script.
parseJSON.groovy
import groovy.json.JsonSlurper
def jsonFile = new File("../var/PARAMS.json")
def keys = new JsonSlurper().parse("jsonFile.text")
println keys.keySet()
I am getting below error :
****No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile.text]****
Can any one please help me ?
Thanks for reply, I am new to this json.
I am unable to share screen shot, showing error message when I am trying to upload image but i can give total error message :
developer#cn-vm-yourname:~/Desktop/kramdeni/vars$ groovy parseJSON.groovy
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile]
Possible solutions: parse(java.io.Reader), parseText(java.lang.String), use([Ljava.lang.Object;), wait(), grep(), any()
groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parse() is applicable for argument types: (java.lang.String) values: [jsonFile]
Possible solutions: parse(java.io.Reader), parseText(java.lang.String), use([Ljava.lang.Object;), wait(), grep(), any()
at parseJSON.run(parseJSON.groovy:3)
developer#cn-vm-yourname:~/Desktop/kramdeni/v
and my expected output is to print only all values without keys in required order.
To get above result I wrote groovy script like below :
import groovy.json.JsonSlurper
label = "test testname params"
def jsonFile = new File('PARAMS.json')
def par = new JsonSlurper().parse(jsonFile)
println keys.keySet()
def command = ""
keys = label.split(" ")
println "keys: " + keys
for (key in keys) {
command += par[key] + " "
}
println "command: " + command

import groovy.json.JsonSlurper
def src = new File("MYPATH/MY.json")
//next line downloads json from URL:
//def src = new URL("http://date.jsontest.com")
def json = new JsonSlurper().parse( src.newInputStream() )
json.each{ k,v-> println "$k = $v" }
try it:
https://groovy-playground.appspot.com/#?load=ccceffd570c6ee176bc6f1fcdafdcbe0
if you have exception
groovy.lang.MissingMethodException: No signature of method:
groovy.json.JsonSlurper.parse() is applicable for argument types:
(java.io.BufferedInputStream)
Possible solutions: parse(java.io.Reader) ...
that means you have quite old version of groovy, however it suggests solution - try to get reader from file:
def src = new File("MYPATH/MY.json")
def json = new JsonSlurper().parse( src.newReader("UTF-8") )
json.each{ k,v-> println "$k = $v" }
but to continue you have to find version of your groovy, then find documentation for your version and continue developing referencing it
for example in groovy 1.8.6 there are only two parse methods in JsonSlurper:
http://docs.groovy-lang.org/1.8.6/html/api/groovy/json/JsonSlurper.html
and in the latest groovy much more...
http://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonSlurper.html

Related

How to compare two JSON responses in groovy and get the differences (similar to what json editor does)?

Can someone please tell me why the error happens and possible alternatives in solving this
My code:
def actual = " [{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8369"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def expected = "[{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8326"}],"lineNumber":620}]}],"__typename":"Source"},"branchExecuted":false},{"inputs":[{"__typename":"ElementalField"}],"constraint":"FILE-STATUS:TRAND-STATUS:TRAND-STATUS-1='0'","source":{"sourceCodeFiles":[{"fileName":"/usr/src/workspace/PC/source/cobol/PCCTRE.cob","sourceLines":[{"nodes":[{"id":"8366"}],"lineNumber":634}]}],"__typename":"Source"},"branchExecuted":false}]"
def removedA = actual.replaceAll("[_]","").trim();
def removedE = expected.replaceAll("[_]","").trim();
def json = new groovy.json.JsonSlurper().parseText(removedA)
//Checks all elements of resource one by one and compare with expectedData
json.each{k, v -> assert v == removedE."$k" }
Here is the error:
groovy.lang.MissingMethodException: No signature of method: Script23$_run_closure1.doCall() is applicable for argument types: (org.apache.groovy.json.internal.LazyMap) values: [[inputs:[[typename:ElementalField]], constraint:FILE-STATUS:REPORT-STATUS:REPORT-STATUS-1='0', ...]] Possible solutions: doCall(java.lang.Object, java.lang.Object), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object) error at line: 37

How to correctly return a json string from python flask server

I am using a python flask server API to call another python flask server API. Both these have been generated using swagger editor.
API2 returns an encoded string such as:
def Server2_API2():
payload = {
"value1": 'somedata',
"value2": 'somedata',
}
encoded_payload = jwt.encode(payload, SECRET, algorithm=ALGORITHM)
return encoded_payload <-- {str}'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.'
API1 on server 1 calls API2 on server 2 as follows:
def Server1_API1():
resp = requests.post('http://localhost:1000/API2', data='value1=one&value2=two')
if resp.status_code == 200:
first_try = resp.content <-- b'"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"\n'
second_try = resp.content.decode() <-- {str} '"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
' <- notice the new line here
return first_try
#return second_try
If I return first_try then I get the error: Object of type 'bytes' is not JSON serializable
If I return second_try then I get the following data returned:
"\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\"\n"
My goal is to have just the data returned as follows without any error or any back slashes or new lines:
e.g. "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
How can I achieve this?
SOLUTION:
third_try = resp.json() <-- This does the trick :)
This did the trick:
token = resp.json()

Parsing the response Json string using groovy

4 for checking the status of the process using httpbuilder and getting the below response.
{"result":[{"id":"167687","dapadmin":"false","status":"in progress","lastupdated":"2017-04-21 14:34:30.0","started":"2017-04-21 14:34:28.0","user":"sys","log":"Running a Stop action\n\nRunning command \n"}]}
Am unable to parse this response using jsonSlurper.parseText() giving error
When I use `
def json = JsonOutput.toJson(statusresponse)
println JsonOutput.prettyPrint(json)
I could see it is printed as json object
{
"result": [
{
"id": "167687",
"dapadmin": "false",
"status": "in progress",
"lastupdated": "2017-04-21 14:34:30.0",
"started": "2017-04-21 14:34:28.0",
"user": "dapsystem",
"log": "Running a Stop action\n\nRunning command \n"
}
]
}
When i check the getClass() , it prints as java.lang.String.
I need to get the lastupdated and status , id values from this response. Please help me to find a solution for this.
Many thanks
Hi Yanpei.
Thanks for the response.
I am using the below code as suggested by you.
def statusresponse = http.putText(baseurl,path,query,headerMap, Method.GET)
println("The status response value is" )
statusresponse.each{ k, v ->
println "${k}:${v}"
}
def json = JsonOutput.toJson(statusresponse)
println "JSON Object List : " + json
println "------------------"
println JsonOutput.prettyPrint(json)
println "The result class is "+json.getClass()
println "The result status is "+(json instanceof Map)
//def entry = slurper.parseText(json)
def slurper = new groovy.json.JsonSlurper()
def entry = slurper.parseText(statusresponse)
def lastupdated = entry.result.lastupdated
checkStatus = entry.result.status
def id = entry.result.id
Am getting the below error
The result class is class java.lang.String
Caught: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.HashMap) values: [[result:[[id:170089, dapadmin:false, status:in progress, ...]]]]
Possible solutions: parseText(java.lang.String), parse(java.io.Reader)
groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.HashMap) values: [[result:[[id:170089, dapadmin:false, status:in progress, ...]]]]
Possible solutions: parseText(java.lang.String), parse(java.io.Reader)
at dap.Main.main(Main.groovy:171)
It works if i use the code as below
def json = JsonOutput.toJson(statusresponse)
def entry = slurper.parseText(json)
Am getting the results as below
The status of the action is :[in progress]
Last updated [2017-04-23 17:08:02.0]
the id is[170088]
First of all, am not sure why the code suggested is throwing this error
Secondly, why i am getting the results for the working solution, within the brackets?
def slurper = new groovy.json.JsonSlurper()
def entry = slurper.parseText('{"result":[{"id":"167687","dapadmin":"false","status":"in progress","lastupdated":"2017-04-21 14:34:30.0","started":"2017-04-21 14:34:28.0","user":"sys","log":"Running a Stop action\n\nRunning command \n"}]}')
def lastupdated = entry.result.lastupdated
def status = entry.result.status
def id = entry.result.id
Should work. Can't see your error so I can't give better info.

Groovy file check

I am a java fresher and I went to an interview recently. They asked a question which was something like: Set up Groovy, test whether a sample json file is valid or not. If it is valid, run the json file. If it is not, print "File is not valid". If file is not found, print "file not found". I was given 2 hours time to do it and I could use the internet.
As I had no idea what groovy was or json was, I searched it and set up groovy but could not obtain the output in two hours. What should I have written? I tried some code but I am sure that it was wrong.
You can use file.exists() to check if the file exists on the filesystem and file.canRead() to check if it can be read by the application. Then use JSONSlurper to parse the file and catch JSONException if the json is invalid:
import groovy.json.*
def filePath = "/tmp/file.json"
def file = new File(filePath)
assert file.exists() : "file not found"
assert file.canRead() : "file cannot be read"
def jsonSlurper = new JsonSlurper()
def object
try {
object = jsonSlurper.parse(file)
} catch (JsonException e) {
println "File is not valid"
throw e
}
println object
To pass the file path argument from the command line, replace def filePath = "/tmp/file.json" with
assert args.size == 1 : "missing file to parse"
def filePath = args[0]
and execute on the command line groovy parse.groovy /tmp/file.json

groovy.json.JsonSlurper parse JSON

I'm trying to parse a JSON-File in my gradle task.
CODE:
def jsonFile = "../files/json/myJSON.json"
def list = new JsonSlurper().parseText(jsonFile)
JSON - FILE
{
"prepare": {
"installed": [],
"uninstalled": []
},
"config": {
"files": []
}
}
But the code gives me the following exception:
Lexing failed on line: 1, column: 1, while reading '.', no possible valid JSON value or punctuation could be recognized.
And I don't understand why, I also validated my JSON-File on http://jsonlint.com/ and it says that it is a valid JSON!
Above code is trying to parse the string ../files/json/myJSON.json as JSON. Instead use:
def jsonFile = new File("../files/json/myJSON.json")
def map = new JsonSlurper().parse(jsonFile)