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.
Related
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
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
I'm looking for a way to convert list of JSON object into an approximate SQLAlchemy model. Is there any implementation?
This is what I did in one of my projects to convert json input from an http request to an sqlalchemy model dynamically:
if request.method == "POST" or request.method == "PUT":
data = request.get_json(force=True)
print("data:", data)
try:
TableClass = models.get_class_by_tablename(table_name)
if TableClass == None: raise Exception("Table not found: %s" % table_name)
if request.method == "POST": #insert data
object = TableClass(**data)
dbsession.add(object)
dbsession.commit()
else: #update data
object = dbsession.query(TableClass).filter_by(**{"id":id}).first()
if object == None: raise Exception("No data found.")
#object.update(**data)
for key in data.keys():
setattr(object, key, data[key])
#dbsession.add(object)
dbsession.commit()
return jsonify({
"status": "success",
"id": object.id,
})
except Exception as e:
return jsonify({
"status": "error",
"error": str(e),
})
data is the variable that gets converted from json input to the usual python dictionary. Then **data is passed as argument for the instance creation of sqlalchemy table class.
I've decided to migrate my Django project to work with SqlAlchemy instead of Django ORM and I'm trying to serialize my SqlAlchemy output to a JSON which contains column names.
In Django I had the following code:
logs = Log.objects.values('log_timestamp', 'message', 'exception', 'level__level', 'job_info__job_name', 'machine', 'user', 'job_report__id').filter(job_info__app_id = app_id).order_by('-time_added')[:1]
logs = json.dumps(list(logs), default=views_utils.default_json_serializer)
print(logs)
and here an output example (contains column names):
[{"user": "user", "level__level": "INFO", "message": "this is a message", "log_timestamp": null, "job_info__job_name": "MongoDB_Maintenance", "exception": "exception details", "machine": "machine", "job_report__id": 65}]
Here is my SqlAlchemy code:
res = session.query(func.DATETIME(LogObj.time_added), LogObj.message, LogObj.exception, LogLevelObj.level, LogObj.machine, LogObj.user).\
join(PeriodicJobInfoObj, LogLevelObj, LogObj,aliased=True).\
filter(PeriodicJobInfoObj.app_id == app_id).\
order_by(desc(LogObj.time_added))[:1]
res = json.dumps(res, default=views_utils.default_json_serializer)
print(res)
The output does not contain column names:
[["2015-09-28 15:36:33", "this is a message", "exception details", "CRITICAL", "machine", "user"]]
default_json_serializer code:
def default_json_serializer(obj):
"""Default JSON serializer."""
import calendar, datetime
if isinstance(obj, datetime.datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
millis = int(
calendar.timegm(obj.timetuple()) * 1000 +
obj.microsecond / 1000
)
return millis
How can I achieve similar output like Django does?
(working with Python 3.4.2)
I have managed to do it this way:
def alchemyencoder(obj):
if isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj)
I use the above encoder when retrieving records in following way:
row = conn.execute(Model.__table__.select())
d = json.dumps([dict(r) for r in row], default=alchemyencoder)
d = json.JSONDecoder().decode(d)
print(d)
show this msg for me
groovy.lang.MissingMethodException: No signature of method: java.io.File.write() is applicable for argument types: (java.lang.Integer, java.lang.String) values: [62, UTF-8] Possible solutions: write(java.lang.String, java.lang.String), write(java.lang.String), wait(), size(), canWrite(), wait(long)
and code is
import groovy.json.JsonSlurper
requestTestStepName = "Criar/Login Usuario 1"
responseContent = testRunner.testCase.getTestStepByName(requestTestStepName).getPropertyValue("response")
response = new JsonSlurper().parseText(responseContent)
userId = response.userId
new File( "C:/tc/json/userId_H24_userid.txt" ).write(userId, "UTF-8")
The answer is staring at you from the really helpful error message..
You need to wrap your 62 userid up as a String:
new File( "C:/tc/json/userId_H24_userid.txt" ).write("$userId", "UTF-8")