java.lang.IllegalArgumentException: Invalid JSON expression: Script1.groovy: 1: unexpected token: ] # line 1, column 36. weather[*].description - rest-assured

I am new to RestAssured and trying to the following code:
#Test
public void testJsonPath() {
Response response = RestAssured
.given()
.param("id", "2172797")
.param("appid", "439d4b804bc8187953eb36d2a8c26a02")
.when()
.get("https://samples.openweathermap.org/data/2.5/weather");
String value = "weather[*].description";
System.out.println(value);
String data = response.then().contentType(ContentType.JSON).extract().path(value);
System.out.println(data);
}
JSON:
{
"coord": {
"lon": 145.77,
"lat": -16.92
},
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03n"
}
],
"base": "stations",
"main": {
"temp": 300.15,
"pressure": 1007,
"humidity": 74,
"temp_min": 300.15,
"temp_max": 300.15
},
"visibility": 10000,
"wind": {
"speed": 3.6,
"deg": 160
},
"clouds": {
"all": 40
},
"dt": 1485790200,
"sys": {
"type": 1,
"id": 8166,
"message": 0.2064,
"country": "AU",
"sunrise": 1485720272,
"sunset": 1485766550
},
"id": 2172797,
"name": "Cairns",
"cod": 200
}
Getting the following error:
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: unexpected token: ] # line 1, column 36.
weather[*].description
Why do we get the following error when using * ?. When replacing it String value = "weather[0].description"; it works fine. Can someone please help me with this.
I have checked the postman as well and the API is giving the correct output.
Note: When using creating code (weather[*].description) from http://jsonpath.com/. It gives the same output.
If there is anything I am missing anything please let me know as I am new to it. Any help to this would be great.
It can also be great if someone can give me a brief on this and let me know whom to refer to get the best output from this.
Why do we get the following error when using * ?. When replacing it String value = "weather[0].description"; it works fine. Can someone please help me with this.

Rest Assured uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax
Official Documentation
GPath
JsonPath
Edit :
{"users":[{"firstName":"sijo","lastName":"john","subjectId":1,"id":1},{"firstName":"sonia","lastName":"sahay","subjectId":2,"id":2},{"firstName":"shreya","lastName":"sahay","subjectId":1,"id":3}],"subjects":[{"id":1,"name":"Devops"},{"id":2,"name":"SDET"}]}
For the above JSON you can use the below to fetch all the lastName
JsonPath abc = new JsonPath(res);
String deal = abc.getString("users.lastName");
System.out.println(deal);

Related

Grafana alerting Error: tsdb.HandleRequest()

I am using Grafana version: v6.7.3 (a04ef6cefc)
After creating a new alert in my widget dashboard, I am seeing the following error:
Error: tsdb.HandleRequest() error bad_response: readObjectStart: expect { or n, but found <, error found in #5 byte of ...|
The error looks to be triggering similar to an alert. Has anyone else encountered something similar to this?
the Error JSON output
{
"firing": true,
"state": "pending",
"conditionEvals": " = true",
"timeMs": "24.602ms",
"error": "tsdb.HandleRequest() error bad_response: readObjectStart: expect { or n, but found <, error found in #5 byte of ...| <!DOCTYPE h|..., bigger context ...| <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transi|...",
"logs": [
{
"message": "Condition[0]: Query",
"data": {
"from": 1637767915735,
"queries": [
{
"refId": "A",
"model": {
"expr": "sum by (code, app_kubernetes_io_instance)(rate(nginx_server_requests{app_kubernetes_io_instance=~\"vue-frontend\",code=~\"4..\"}[1m]))",
"format": "time_series",
"hide": false,
"instant": false,
"interval": "",
"intervalFactor": 1,
"legendFormat": "{{code}} on {{app_kubernetes_io_instance}}",
"refId": "A"
},
"datasource": {
"id": 14,
"name": "somesomain.com"
},
"maxDataPoints": 0,
"intervalMs": 0
}
],
"to": 1637768215735
}
}
]
}

Get value from json based on condition using JsonPath

I've following json -
{
"issues": [{
"id": 200615,
"custom_fields": [{
"id": 166,
"name": "Severity",
"internal_name": null,
"field_format": "list",
"value": "Major"
}, {
"id": 167,
"name": "Reproducibility",
"internal_name": null,
"field_format": "list",
"value": "Always"
}, {
"id": 168,
"name": "Resolution",
"internal_name": null,
"field_format": "list",
"value": "open"
}]
}]
}
Out of this json I want to get value of issues -> custome_fields -> value where id is 167 and expected value is - Always (167 can be at any position in json hence can't hardcode it)
Could you please how I can achieve the value?
jsonPath.get("issues[0].custom_fields[?(#.id == '167')].value[0]")
results into error -
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 50.
Object.issues[0].custom_fields[?(#.id ==
I get the same error as you do and I don't know why.
However, you can achieve the same goal using findAll json path method like this:
issues[0].custom_fields.findAll { it.id == 167 }.value[0]
Prints out: Always
$.issues[0].custom_fields[?(#.id==167)].value

Trying to parse an json file with Swifty JSON

i'm practicing with Alamofire and SwiftyJSON in Swift, but I have a problem.
I'm trying to get an element in JSON that is in a diferent level, but it keeps me showing nil or null, or the fields it's empty.
Although I'm using the marvel developer app.
My Code:
Alamofire.request(urlGetCharaters).responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
print("Pa ti")
print(json["data"]["results"]["name"].stringValue)
}
It's keep me saying that is empty.
The Json is this:
"code": 200,
"status": "Ok",
"copyright": "© 2018 MARVEL",
"attributionText": "Data provided by Marvel. © 2018 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2018 MARVEL",
"etag": " ",
"data": {
"offset": 0,
"limit": 20,
"total": 1491,
"count": 20,
"results": [
{
"id": 1011334,
"name": "3-D Man",
"description": "",
"modified": "2014-04-29T14:18:17-0400",
"thumbnail": {
"path": "http://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784",
"extension": "jpg"
},
I'm trying to get in: data -> results and then get "name".
Any solution? Thanks
As commented by rmaddy, you should get first result name like this:
print(json["data"]["results"][0]["name"].stringValue)
Don't forget array and object are different.

In Watson Discovery, limiting "return"ed fields to aggregation values

For the Discovery REST api, the argument/parameter "return" controls which fields are returned.
So if I pass these arguments to the API
{
"query": named_sector,
"count": "10",
"filter": filter_dates,
"aggregation" : "term(docSentiment.type,count:3)"
}
my_query = discovery.query(my_disc_environment_id, my_disc_collection_id, qopts)
print(json.dumps(my_query, indent=2))
I get the following:
{
"matching_results": 14779,
"aggregations": [
{
"type": "term",
"field": "docSentiment.type",
"count": 3,
"results": [
{
"key": "positive",
"matching_results": 4212
},
{
"key": "negative",
"matching_results": 3259
},
{
"key": "neutral",
"matching_results": 152
}
]
}
],
"results": [
{
"id": "6389715fe7e7f711e0bc09d4f1236639",
"score": 1.3689895,
"yyyymm": "201704",
"url": "https://seekingalpha.com/article/4060446-valuation-dashboard-consumer-discretionary-update",
"enrichedTitle": null,
"host": "seekingalpha.com",
"text": "Valuation Dashboard: Consumer Discretionary - Update\n\nSummary\n\nValuation metrics in Consumer Discretionary.\n\nEvolution since last month.\n\nA list of stocks loo ....
and thousands of more lines. How do I restrict the output to the aggregations section? Is this an issue of me better handling the JSON structure that is returned?
thanks
If you change the count argument to 0, the returned JSON will only contain the aggregations.
Also, if you're using the Discovery web tooling, you can enter 0 for the "Number of results to return (Count)" field.
More details and an example can be found here: https://www.ibm.com/watson/developercloud/doc/discovery/using.html#building-aggregations

Rails: Fetch JSON Data from Remote URL / API Call

i am trying to fetch a json data in my rails app from a url. how to make this api call.
{
"name": "MagicList",
"count": 20,
"frequency": "realtime",
"version": 5,
"newdata": true,
"lastrunstatus": "success",
"lastsuccess": "Sat Apr 26 2014 14:34:40 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"Title": {
"href": "http://www.magicbricks.com/propertyDetails/2-BHK-746-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-79-in-Gurgaon&id=C0gt4k2Fa9tzpSvf+uAgZw==",
"text": "2 BHK Multistorey Apartment in Sector-79"
},
"Price": "37.99 Lac(s)",
"Rate": "5,092",
"Size": "746 Sq-ft",
"Project Name": "",
"New_Resale": "New Property"
},
{
"Title": {
"href": "http://www.magicbricks.com/propertyDetails/2-BHK-1050-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-68-in-Gurgaon&id=M5jckQCuJaBzpSvf+uAgZw==",
"text": "2 BHK Multistorey Apartment in Sector-68"
},
"Price": "57.50 Lac(s)",
"Rate": "5,476",
"Size": "1050 Sq-ft",
"Project Name": "Project: Pareena Sec68",
"New_Resale": "New Property"
},
{
"Title": {
"href": "http://www.magicbricks.com/propertyDetails/3-BHK-1875-Sq-ft-Multistorey-Apartment-FOR-Sale-Sector-37C-in-Gurgaon&id=gw8zjmcA/b1zpSvf+uAgZw==",
"text": "3 BHK Multistorey Apartment in Sector-37C"
},
"Price": "60.0 Lac(s)\nOnwards",
"Rate": "3,200",
"Size": "1875 Sq-ft",
"Project Name": "Project: Spire Greens",
"New_Resale": "Resale"
}
}
}
dont know how it can be achieved, which gem should be used.
Using 'open-uri'
url = "http://..."
data = JSON.parse(open(url).read)
Or using 'net'
require "net/http"
url = "http://..."
resp = Net::HTTP.get_response(URI.parse(url))
data = JSON.parse(resp.body)
This is not an answer to your question, but stack overflow won't let me post a comment without 50 reputation.
You may want to edit your API key out of your question, since it's the equivalent of your password for using their API services.
Yes you can easily use builtin stuff:
uri = "https://yourapithinkg.com/list?api_key=#{ENV.fetch('API_KEY')}"
result = JSON.parse(Net::HTTP.get(URI.parse(uri)))
Most people like to load in other libraries but its not really worth it.

Resources