I am trying to parse a single value from a REST web service that I am testing.
I understand how to make the call and I see the JSON response in the Output window.
let request = Alamofire.request(.GET, "http://IP:PORT/jsonTest", parameters: ["s": "Ping?"])
.responseJSON{(_,_,data,_) in
var json = JSON(data!)
println(json)
The Console Output shows me:
{"NewDataSet":[
{"Table1":[
{"Column-A":"FirstA",
"Column-B":"FirstB"
},
{"Column-A":"SecondA",
"Column-B":"SecondB"
},
{"Column-A":"ThirdA",
"Column-B":"ThirdB"
}
]}
]}
What I would like to do now, is to display only the first value from Column-A - which in this example would be "FirstA".
I've been trying to use a code like this, but so far I am not getting anywhere...
println(json[0][0]["Column-A"].stringValue)
Any pointers much appreciated!
json["NewDataSet"][0]["Table1"][0]["Column-A"].stringValue
This is what you want. This is because your json starts with a dictionary and is formatted as dictionary>array>dictionary>array>dictionary. Note that json dictionaries are noted by { : , : } while arrays are noted as [ , ].
Related
I need to pass a json string as a value to one parameter of a POST request body. My request body looks like this:
"parameter1":"abc",
"parameter2":"def",
"parameter3": "{\"id\":\"\",\"key1\":\"test123\",\"prod1\":{\"id\":\"\",\"key3\":\"test123\",\"key4\":\"12334\",\"key5\":\"3\",\"key6\":\"234334\"},\"prod2\":{\"id\":\"\",\"key7\":\"test234\",\"key8\":1,\"key9\":true}}\"",
"parameter4":false,
"parameter5":"ghi"
}
For parameter3 I need to be pass a string value in json format. The json file is located in my local system and is a huge file, so it would make sense if I can pass it as a jmeter variable. I tried as below:
{
"parameter1":"abc",
"parameter2":"def",
"parameter3": "${jsonObj}",
"parameter4":false,
"parameter5":"ghi"
}
after adding a JSR223 preprocessor with the code below:
import org.apache.jmeter.util.JMeterUtils;
String fileContents = new File("path to json//myJson.json").getText('UTF-8');
vars.put("fileContents",fileContents);
var deltaJson = vars.get("fileContents");
var jsonObj = JSON.parse(deltaJson);
vars.put("jsonObj", JSON.stringify(jsonObj));
But I get below error:
exceptions":{"exceptionType":"System.JSONException","exceptionMessage":"Unexpected character ('$' (code 36)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]"}
Can anyone help me in resolving this issue?
There is an easier way of doing this, JMeter comes with __FileToString() function so you can achieve the same much faster and without having to do any scripting
Something like:
{
"parameter1": "abc",
"parameter2": "def",
"parameter3": ${__FileToString(path to json//myJson.json,UTF-8,jsonObj)},
"parameter4": false,
"parameter5": "ghi"
}
Also be aware of the following facts:
the recommended language for using in JSR223 Test Elements is Groovy as it provides the maximum performance
you seem to be using JSON object which cannot be used outside of the browser context therefore your code fails to generate proper JSON hence your request fails as you're passing ${jsonObj} as it is, the substitution doesn't happen, you can look to jmeter.log file yourself and see the exact reason of your script failure
I am getting below response from a REST API, but I am finding it difficult to extract label value from the received response and assign it to a variable to use it later in script.
Here is the RESPONSE::
{
"result": "SUCCESS",
"rawAttr": "[{\"attributes\":[{\"name\":\"resourceid\",\"value\":\"7A7Q123456\"},{\"name\":\"physicalid\",\"value\":\"7A7Q123456\"},{\"name\":\"dsw:label\",\"value\":\"MY Product00004285\"},{\"name\":\"dsw:created\",\"value\":\"2019-11-06T08:39:39Z\"}]}]",
"physicalid": "7A7Q123456",
"contextPath": "/path",
"id": "7A7Q123456",
"message": null
}
I am able to get response.id and response.result which is helpful for validation but I am not able to get the dsw:label value which is MY Product00004285
When I do def Arr = response.rawAttr I get the below value whether it is Array or String I am confused. Seems like it is a string.
[{"attributes":[{"name":"resourceid","value":"7A7Q123456"},{"name":"physicalid","value":"7A7Q123456"},{"name":"dsw:label","value":"MY Product00004298"},{"name":"dsw:created","value":"2019-11-06T08:39:39Z"}]}]
It is very easy to extract the label in JMeter JSON Extractor using below JSON Path expression
$.attributes.value[2]
Refer Karate's type conversion capabilities: https://github.com/intuit/karate#type-conversion
So you can do this:
* json attr = response.rawAttr
And then you are all set.
Thanks to an example and documentation on converting string to json.
Got it how to do.
And def strVar = response.rawAttr
And json jsonVar = strVar
And def attrb = karate.jsonPath(jsonVar, '$..attributes.[2].value')[0]
And print '\n\n Attrb\n', attrb
Links I referred:
Json Path evaluator
Karate doc reference for type conversion
Karate example for type-conversion
I am storing the response of a REST Get request and trying to access as below,
final JSONObject receivedItem = new JSONObject(response.readEntity(String.class));
This is the sample response,
[
{
"timeStamp": 1511136000000,
"contextKeys": [
{
"tKey": "Test1",
"contextKey": "Location",
"contextValue": "San Jose",
"eCount": 3
},
{
"tKey": "Test1",
"contextKey": "Name",
"contextValue": "User1",
"eCount": 3
}
}
]
And i am getting the below error,
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
Any clues ?
Thanks
As Rajkumar pointed out, in your example there is a missing close bracket - but this may just be a simple typing error.
The actual error message is saying A JSONObject text must begin with '{' which is because JSON objects are exactly that, objects. You need to use a JSONArray to parse your example JSON as follows:
final JSONArray receivedItem = new JSONArray(response.readEntity(String.class));
This may change some of your other code to handle this as an array vs an object.
If your problem is with storing and accessing json response try this response instead;
I am presuming that you are using javascript; Anyways, core idea is the same;
var jsonStorage;
$.getJSON('your url',(json) => {
jsonStorage = json;
});
console.log(jsonStorage) //your jsonresponse is now available here;
so i have this data which is outputted from stringify(doc)
{
"id": "8467fdae-c38c-4b6e-9492-807d7c9eb97e",
"message": "send to nodejs"
}
but im not sure how can i go ahead in getting a single value from it, e.g message. Any help would be appreciated as ive tried different methods and they seem to not be working
After you use stringify method the value you have is string.
So You can not get single property from it, except you convert it become object again and get property it. Like this:
object = {
"id": "8467fdae-c38c-4b6e-9492-807d7c9eb97e",
"message": "send to nodejs"
};
// JSON string is value which you get after use Stringify method
jsonString = JSON.stringify(object);
// Convert jsonString to object again and get message property
message = JSON.parse(jsonString).message
stringify() will convert json to string.
Before running stringify(), doc is already json and you can get message by doc.message.
after running stringify(), the result will be string, if you want to get json back, you can use JSON.parse()
I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types