(eosjs) How to fetch a row with string type - eos

In A.cpp, there is starinfo struct and memo property of string type.
struct starinfo{
uint64_t num;
account_name account;
asset price;
string memo;
}
I published contract, and wrote some value using push action.
This is result. (cleos.sh get table aaaa0000aaaa0000 aaaa0000aaaa0000 starinfo)
{
"rows": [{
"num": 0,
"account": "aaabbbcccddd",
"price": "1.0000 EOS",
"memo": "M"
}
],
"more": false
}
But when I use eos.getTableRows below error occured.
"Unable to unpack built-in type 'string' while processing 'starinfo.memo'"
In detail,
Error: {"code":500,"message":"Internal Service Error","error":{"code":3015013, "name":"unpack_exception","what":"Unpack data exception","details":[{"message" :"Unable to unpack built-in type 'string' while processing 'starinfo.memo'","f ile":"abi_serializer.cpp","line_number":327,"method":"_binary_to_variant"},{"m essage":"read datastream of length 58 over by -40","file":"datastream.cpp","li ne_number":6,"method":"throw_datastream_range_error"}]}}
When I fetch a row under cleos console, it works. But when i fetch a row using eosjs, it doesn't work.

Related

Filtering JSON data with equality operator

Given the query
#.records[*].issues[].[type, message]
on the JSON
{
"records":[
{
"id":"db7bb828-60e2-5fa8-048c-06542abd98d2",
"parentId":"3dc8fd7e-4368-5a92-293e-d53cefc8c4b3",
"type":"Task",
"name":"PublishBuildArtifacts",
"startTime":"2022-09-28T14:06:41.3266667Z",
"finishTime":"2022-09-28T14:06:41.3266667Z",
"currentOperation":null,
"percentComplete":null,
"state":"completed",
"result":"skipped",
"resultCode":"Evaluating: SucceededNode()\r\nResult: False\r\n",
"changeId":29,
"lastModified":"0001-01-01T00:00:00",
"workerName":"AgentSalam7WithPat",
"order":19,
"details":null,
"errorCount":0,
"warningCount":0,
"url":null,
"log":null,
"task":{
"id":"2ff763a7-ce83-4e1f-bc89-0ae63477cebe",
"name":"PublishBuildArtifacts",
"version":"1.158.3"
},
"attempt":1,
"identifier":null
},
{
"id":"d56f7c92-f706-53be-685b-17b89c98baa6",
"parentId":"3dc8fd7e-4368-5a92-293e-d53cefc8c4b3",
"type":"Task",
"name":"SonarQubePublish",
"startTime":"2022-09-28T14:06:31.7066667Z",
"finishTime":"2022-09-28T14:06:41.31Z",
"currentOperation":null,
"percentComplete":null,
"state":"completed",
"result":"failed",
"resultCode":null,
"changeId":31,
"lastModified":"0001-01-01T00:00:00",
"workerName":"AgentSalam7WithPat",
"order":11,
"details":null,
"errorCount":1,
"warningCount":0,
"url":null,
"log":{
"id":14,
"type":"Container",
"url":"https://azuredevops2k19.salam.net/Sierac-Utilities/6f9f1b22-cd2b-4ed4-a2c9-37822128b7c6/_apis/build/builds/201/logs/14"
},
"task":{
"id":"291ed61f-1ee4-45d3-b1b0-bf822d9095ef",
"name":"SonarQubePublish",
"version":"5.0.1"
},
"attempt":1,
"identifier":null,
"issues":[
{
"type":"error",
"category":"General",
"message":"[SQ] Task failed with status FAILED, Error message: Fail to extract report AYOEa2gdtfNdJFd6edM9 from database",
"data":{
"type":"error",
"logFileLineNumber":"9"
}
},
{
"type":"warning",
"category":"General",
"message":"Unable to get default branch, defaulting to 'master': Error: enable to verify the first certificate",
"data":{
"type":"warning",
"logFileLineNumber":"10"
}
}
]
}
]
}
I get the resulting JSON:
[
[
"error",
"[SQ] Task failed with status FAILED, Error message: Fail to extract report AYOEa2gdtfNdJFd6edM9 from database"
],
[
"warning",
"Unable to get default branch, defaulting to 'master': Error: enable to verify the first certificate"
]
]
Now I need to add a filter like [type = error], so I only get the messages of type error.
How can this be achieved? In the documentation, this is not very clear to me.
Filtering and multiselect lists do need a question mark in the array notation brackets – [?this > `that`] – and the equality test is a double equal sign – ==.
So your query should be:
#.records[*].issues[?type == `error`].[type, message]
Which gives the resulting JSON:
[
[
[
"error",
"[SQ] Task failed with status FAILED, Error message: Fail to extract report AYOEa2gdtfNdJFd6edM9 from database"
]
]
]
Should you need to flatten the multiple arrays of arrays, you can use the flatten operator, and with the query:
#.records[*].issues[?type == `error`].[type, message][][]
You will, then, end up with this resulting JSON:
[
"error",
"[SQ] Task failed with status FAILED, Error message: Fail to extract report AYOEa2gdtfNdJFd6edM9 from database"
]

How to fetch an attribute value from a variable, having the content of a JSON response

I'm using the Robot Framework API automation. Here, storing the JSON response in a variable [POSTResp.content]. I.e., "POSTResp.content" has the whole response, as given below. Please help me to get an attribute's value (for ex, value of referenceId) from the stored content.
Example of JSON response:
{
"serviceResponseHeader": {
"responseContext": {
"responseCode": "MS19",
"responseDescription": "Success",
"serviceResponseTimeInGMT": "18 Sep 2018 16:12:43 GMT"
},
"requesterContext": {
"applicationCode": null,
"applicationSubCode": null,
"countryCode": null,
"requesterReferenceNumber": null,
"requestTimeInGMT": "30 Jun 2015 11:54:49 GMT",
"requesterUserIdentity": "23483",
"requesterGroupIdentity": "1620",
"requesterIpAddress": "",
"sessionIdentity": "2536kjhfdashfkhfsab",
"ssoSessionIdentity": "2536kjhfdashfkhfsab",
"requesterAbbreviatedGroupName": "NEWCOMP"
},
"serviceContext": {
"serviceVersionNumber": "1.0",
"serviceCode": "30"
}
},
"getProxyDetailResponseBody": {
"proxyDetails": {
"proxyType": "",
"proxyValue": "20140005K",
"referenceId": "PR18090000847597",
"transactionId": "18091801657466"
}
}
}
I've tried the below ways,
1) ${json} To JSON ${POSTResp.content} true
log to console \n the Proxy ID is ${json["proxyValue"]}
Result: Resolving variable '${json["proxyValue"]}' failed: TypeError: string indices must be integers, not str
2) ${json} Evaluate json.loads(${POSTResp.content}} json
log to console \n the Proxy ID is ${json["proxyValue"]}
Result: failed: SyntaxError: unexpected EOF while parsing (, line 1)
Issues with your two approaches:
1) the library keyword call passes a true argument (well, truth-like) to the pretty_print parameter:
${json} To JSON ${POSTResp.content} true
Looking at the library's source, in that case the keyword does not return a dict object - but a string, a beatified version of the source json. That coincides with the error your received.
Remove the "true" argument and it must return a dict.
2) In the Evaluate surround the variable with triple quotes (python's literal string):
${json} Evaluate json.loads('''${POSTResp.content}'''}
json
Without it, the framework just dumped the variable's value, which raised a python syntax error.
By the way, try not to make your variables with language keywords/library names - like ${json} up there.

Can JSON String format be converted to Actual format using groovy?

I have the following JSON String format getting from external source:-
What kind of format is this actually?
{
id=102,
brand=Disha,
book=[{
slr=EFTR,
description=Grammer,
data=TYR,
rate=true,
numberOfPages=345,
maxAllowed=12,
currentPage=345
},
{
slr=EFRE,
description=English,
data=TYR,
rate=true,
numberOfPages=345,
maxAllowed=12,
currentPage=345
}]
}
I want to convert this into actual JSON format like this: -
{
"id": "102",
"brand": "Disha",
"book": [{
"slr": "EFTR",
"description": "Grammer",
"data": "TYR",
"rate": true,
"numberOfPages": 345,
"maxAllowed": "12",
"currentPage": 345
},
{
"slr": "EFRE",
"description": "English",
"data": "TYR",
"rate": true,
"numberOfPages": 345,
"maxAllowed": "12",
"currentPage": 345
}]
}
Is this achievable using groovy command or code?
Couple of things:
You do not need Groovy Script test step which is currently there as step3
For step2, Add a 'Script Assertion` with given below script
Provide step name for nextStepName in the script below for which you want to add the request.
//Provide the test step name where you want to add the request
def nextStepName = 'step4'
def setRequestToStep = { stepName, requestContent ->
context.testCase.testSteps[stepName]?.httpRequest.requestContent = requestContent
}
//Check the response
assert context.response, 'Response is empty or null'
setRequestToStep(nextStepName, context.response)
EDIT: Based on the discussion with OP on the chat, OP want to update existing request of step4 for a key and its value as step2's response.
Using samples to demonstrate the change input and desired outputs.
Let us say, step2's response is:
{
"world": "test1"
}
And step4's existing request is :
{
"key" : "value",
"key2" : "value2"
}
Now, OP wants to update value of key with first response in ste4's request, and desired is :
{
"key": {
"world": "test1"
},
"key2": "value2"
}
Here is the updated script, use it in Script Assertion for step 2:
//Change the key name if required; the step2 response is updated for this key of step4
def keyName = 'key'
//Change the name of test step to expected to be updated with new request
def nextStepName = 'step4'
//Check response
assert context.response, 'Response is null or empty'
def getJson = { str ->
new groovy.json.JsonSlurper().parseText(str)
}
def getStringRequest = { json ->
new groovy.json.JsonBuilder(json).toPrettyString()
}
def setRequestToStep = { stepName, requestContent, key ->
def currentRequest = context.testCase.testSteps[stepName]?.httpRequest.requestContent
log.info "Existing request of step ${stepName} is ${currentRequest}"
def currentReqJson = getJson(currentRequest)
currentReqJson."$key" = getJson(requestContent)
context.testCase.testSteps[stepName]?.httpRequest.requestContent = getStringRequest(currentReqJson)
log.info "Updated request of step ${stepName} is ${getStringRequest(currentReqJson)}"
}
setRequestToStep(nextStepName, context.request, keyName)
We can convert the invalid JSON format to valid JSON format using this line of code:-
def validJSONString = JsonOutput.toJson(invalidJSONString).toString()

Python3 json output values to file line by line only if other fields are greater than value

I have retrieved remote json using urllib.request in python3 and would like to to dump, line by line, the value of the IP addresses only (ie. ip:127.0.0.1 would be 127.0.0.1, next line is next IP) if it matches certain criteria. Other key values include a score (one integer value per category) and category (one or more string values possible).
I want to check if the score is higher than, say 10, AND the category number equals a list of one OR more values. If it fits the params, I just need those IP addresses added line by line to a text file.
Here is how I retrieve the json:
ip_fetch = urllib.request.urlopen('https://testonly.com/ip.json').read().decode('utf8')
I have the json module loaded, but don't know where to go from here.
Example of json data I'm working with, more than one category:
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
I wrote a simple example that should show you how to iterate trough json objects and how to write to a file:
import json
j = json.loads(test)
threshold = 10
validCategories = ["Test"]
f=open("test.txt",'w')
for ip, categories in j.items():
addToList = False
for category, rank in categories.items():
if category in validCategories and int(rank) >= threshold:
addToList = True
if addToList:
f.write("{}\n".format(ip))
f.close()
I hope that helps you to get started. For testing I used the following json-string:
test = """
{
"127.0.0.1" : {
"Test" : "10",
"Prod" : "20"
},
"127.0.0.2" : {
"Test" : "5",
"Prod" : "20"
},
"127.0.0.3" : {
"Test" : "5",
"Prod" : "5",
"Test2": "20"
}
}
"""

i got empty value when print json key in lua code

this is the json response plus "\x00" in the end from server :
{
"STATUS": [{
"STATUS":"S",
"When":1470180059,
"Code":11,
"Msg":"Summary",
"Description":"nsgminer 0.9.2"
}],"SUMMARY": [{
"Elapsed":2061,
"MHS av":0.00,
"Found Blocks":0,
"Getworks":76,
"Accepted":0,
"Rejected":0,
"Hardware Errors":0,
"Utility":0.00,
"Discarded":209,
"Stale":0,
"Get Failures":3,
"Local Work":293,
"Remote Failures":0,
"Network Blocks":14,
"Total MH":0.0000,
"Work Utility":0.00,
"Difficulty Accepted":0.00000000,
"Difficulty Rejected":0.00000000,
"Difficulty Stale":0.00000000,
"Best Share":0
}],
"id":1
}\x00
i want to use the json in lua code :
local output = stdnse.output_table()
local json_string = tostring(result:sub(1, -2))
local pos, value = json.parse(json_string)
output["Description"] = value["STATUS"][0]["Description"]
return output
when i print it out, i got null value
i solve that with covert json to string and convert string into json table
local pos, value = json.parse(tostring(json_string))
output["Description"] = value["STATUS"][1]["Description"]