unable to read key from json using JsonPath - java

I am trying to read a json value by providing json key.
code that i am tried. document is alreadt load it has above json.
i am using this link https://github.com/jayway/JsonPath
jsonPath = "$.Contact[?(#.key =~ /ContactID/i)].value";
Object attrValue = JsonPath.read(document, jsonPath);
"attrValue is empty". please guide me on this. thanks in advance
{
Date=/Date(1454410800000+1300)/,
Type=ACCREC,
Total=7000,
Status=PAID,
Contact={
Name=Abc,
Phones=[
],
Addresses=[
],
ContactID=df400dcd-6bdb-4cb5-98ce-496ec64c253f,
ContactGroups=[
],
ContactPersons=[
],
HasValidationErrors=false
},
DueDate=/Date(1454756400000+1300)/,
SubTotal=7000,
TotalTax=0,
AmountDue=0,
HasErrors=false,
InvoiceID=7aaa5fe5-25c3-47f9-b37f-f732b7705ee4
}

Related

How to send multiple JSON in single request(Jmeter)

Though I could see this question might be repeated but couldn't find any similar solution for the below JSON strut. Pls suggest.
I have excel sheet where the data's in columns look like :
CSV file data
My expected JSON as:
{
"Child ": {
"10"
: { "Post": { "Kid-R":1 },
"Var": [1,1 ],
"Tar": [2,2],
"Fur": [3,3]},
"11":
{"Post": {"Kid-R":2 },
"Var": [1,1 ],
"Tar": [2,2 ],
"Fur": [5,4 ]}
},
"Clone": [],
"Birth": 2,
"TT": 11,
"Clock": ${__time(/1000,)}
}
I have tried incorporating beanshell preprocessor in JMeter & tried below code:
def builder = new groovy.json.JsonBuilder()
#groovy.transform.Immutable
class Child {
String post
String var
String Tar
String Fur
}
def villas = new File("Audit_27.csv")
.readLines()
.collect { line ->
new child (line.split(",")[1],(line.split(",")
[2]+","+line.split(",")[3]),(line.split(",")[4]+","+line.split(",")
[5]),(line.split(",")[6]+","+line.split(",")[7]))}
builder(
Child :villas.collect(),
"Clone": [],
"Birth": 2,
"TT": 11,
"Clock": ${__time(/1000,)}
)
log.info(builder.toPrettyString())
vars.put("payload", builder.toPrettyString())
And I could see below response only:
Note: I dont know how to declare "Key" value (line.split(",")[0]) in the above solution.
{
"Child": [
{
"post": "\"\"\"Kid-R\"\":1\"",
"var": "\"[2,2]\"",
"Tar": "\"[1,1]\"",
"Fur": "\"[3,3]\""
},
{
"post": "\"\"\"Kid-R\"\":2\"",
"var": "\"[2,2]\"",
"Tar": "\"[1,1]\"",
"Fur": "\"[3,3]\""
}
],
"Clone": [],
"Birth": 2,
"TT": 11,
"CLock": 1585219797
}
Any help would be greatly appreciated
You're copying and pasting the solution from this answer without understanding what you're doing.
If you change class name from VILLA to own you need to use new own instead of new VILLA
Also this line won't compile: Clock: <take system current time> you need to use System.currentTimeMillis() or appropriate function of the Date class in order to generate the timestamp.
If you want a comprehensive answer, you need to provide:
Well-formatted CSV file
Valid JSON payload
In the meantime I would recommend getting familiarized with the following material:
Apache Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Reading a File in Groovy
Actually I am gonna follow DmirtiT suggestions, as mentioned in some of post to use random variable for bulk API request. Same answer it helped me here as well to generate multiple JSON structure with unique data. Thanks..

Parse array in JSON using JsonPath in Java

I am using jayway JsonPath library to parse the JSON using the path given. I am able to get the string value if I give the correct path. But I want to get the list of maps when I give the path if its an array. For example, I have a JSON like below:
{
"employees": {
"company": "Google",
"people": [{
"name": "John",
"age": 25,
"location": "zurich"
},
{
"name": "Peter",
"age": 27,
"location": "Lucerene"
}]
}
}
Below is the code I am using to parse the json.
if I give the path $.employees.people, I am getting the String, But I need to List of Maps. Below is the code I am using to Parse Json using jsonpath.
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath) //But this is returning String
Anyone suggest proper approach to get what I expected.
try using,
DocumentContext documentContext = JsonPath.parse(jsonStr);
JsonPath jsonPath = JsonPath.compile("$.employees.people[?]");
List<Maps<String,String>> jsonList = documentContext.read(jsonPath);
if you need more details. readmore...

How to extract a particular value from Json Node?

Hi I have Input of JsonNode type as follows:
{
"Records": [
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:us-west-1:270252992114:d1dd43d0-8bf1-496c-bc94-f4e70dec5032",
"Sns": {
"Type": "Notification",
"MessageId": "923d528f-c844-5d49-95de-018f6d583bfd",
"TopicArn": "arn:aws:sns:us-west-1:270252992114:",
"Subject": null,
"Message": "AAAAAQAAAAAAAAABAAAAJGNvbS5hbWF6b24uY3VzdG9tZXJldmVudC5jZXMudGVzdC5OQQAAABDW7HxyIs4PvuXtarSxIxdeAAABALZT+4Yv09z9tK48/miZ6IhjvVCLixiH3GLltCxQzEkNgf9NTD57G744vdnw1D3LxLmxT4i0CCkVJJ5IPaH3Ud5Oy6MKa5wRrldtS6MTDMzKqoPwcdMiLm3AogonUAqyBYrxWt8fHrCYIlggX9EFW9Dk9ugDRrJuhCZqfVnt/wRUyP33DycwRKHBHSxn1XuDi9ZyEeCxrMLn9rGmpVvUQb3mdFReoVDmP4cEWcQEwYxG6/WvyimHGD5JtSxzlCR3rwddu8vXlp9Mq127+scPipAm83IJSw7CS5laZQZAD8qR4WwSfSZw8kq72y/LulhzWj3w7jbtOtmhbdnPyIN+L4I=",
"Timestamp": "2018-02-16T09:22:36.149Z",
"SignatureVersion": "1",
"Signature": "f+23JQ6r9gZL6dRay4wqJHrX5CnB9cSVpPS/zgopPKHFOD5zvEpuTiGfuNf0e2L6/84pm6gK9xCEakzeaWtBAp7J/hFfbKQ2BSJ/GAKX1peG16Q8TS2k0NVxjzG4ImEHxf3i3ODOFJeA7WHxRZiMkNO+79lZDxkkOQdfWR3OEQ1yP8CjE4HLlLoSEUdk170AOw1nty9NZ6FOnsotLf5jce0GrXs1lkn7J/3nv/YlSqdMZEAR4SZDELCH3krQ4mUO7gwUfkDSFXsjWLarTayYl20eH3g/RZLQgPEQGTRBZW5wrknXg1vm4H4ICxxrGJBooAs7BCLkUVT1m4juRrlljA==",
"SigningCertUrl": "https://sns.us-west-1.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem",
"UnsubscribeUrl": "https://sns.us-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-1:270252992114:",
"MessageAttributes": {}
}
}
]
}
I want to extract value of TopicArn and Message, I tried following code but rawSns is coming as null:
JsonNode rawResource = input.get("Records");
logger.log("rawResource is: " + rawResource);
JsonNode rawSns = rawResource.get("Sns");
Does anyone can help me out in this?
You can use following:
JsonNode rawResource = input.get("Records");
logger.log("rawResource is: " + rawResource);
JsonNode rawSns = rawResource.get(0).get("Sns");
See here for Javadoc
This is precisely what you need.
var jsonObject = JSON.parse('{"Records":[{"EventSource":"aws:sns","EventVersion":"1.0","EventSubscriptionArn":"arn:aws:sns:us-west-1:270252992114:d1dd43d0-8bf1-496c-bc94-f4e70dec5032","Sns":{"Type":"Notification","MessageId":"923d528f-c844-5d49-95de-018f6d583bfd","TopicArn":"arn:aws:sns:us-west-1:270252992114:","Subject":null,"Message":"AAAAAQAAAAAAAAABAAAAJGNvbS5hbWF6b24uY3VzdG9tZXJldmVudC5jZXMudGVzdC5OQQAAABDW7HxyIs4PvuXtarSxIxdeAAABALZT+4Yv09z9tK48/miZ6IhjvVCLixiH3GLltCxQzEkNgf9NTD57G744vdnw1D3LxLmxT4i0CCkVJJ5IPaH3Ud5Oy6MKa5wRrldtS6MTDMzKqoPwcdMiLm3AogonUAqyBYrxWt8fHrCYIlggX9EFW9Dk9ugDRrJuhCZqfVnt/wRUyP33DycwRKHBHSxn1XuDi9ZyEeCxrMLn9rGmpVvUQb3mdFReoVDmP4cEWcQEwYxG6/WvyimHGD5JtSxzlCR3rwddu8vXlp9Mq127+scPipAm83IJSw7CS5laZQZAD8qR4WwSfSZw8kq72y/LulhzWj3w7jbtOtmhbdnPyIN+L4I=","Timestamp":"2018-02-16T09:22:36.149Z","SignatureVersion":"1","Signature":"f+23JQ6r9gZL6dRay4wqJHrX5CnB9cSVpPS/zgopPKHFOD5zvEpuTiGfuNf0e2L6/84pm6gK9xCEakzeaWtBAp7J/hFfbKQ2BSJ/GAKX1peG16Q8TS2k0NVxjzG4ImEHxf3i3ODOFJeA7WHxRZiMkNO+79lZDxkkOQdfWR3OEQ1yP8CjE4HLlLoSEUdk170AOw1nty9NZ6FOnsotLf5jce0GrXs1lkn7J/3nv/YlSqdMZEAR4SZDELCH3krQ4mUO7gwUfkDSFXsjWLarTayYl20eH3g/RZLQgPEQGTRBZW5wrknXg1vm4H4ICxxrGJBooAs7BCLkUVT1m4juRrlljA==","SigningCertUrl":"https://sns.us-west-1.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem","UnsubscribeUrl":"https://sns.us-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-1:270252992114:","MessageAttributes":{}}}]}');
console.log(((jsonObject["Records"][0])["Sns"])["TopicArn"]);
This online tool can help you understand the structure of your JSON : JSON viewer.

How to convert nested Json in string into Json object in java

I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar

how to iterate json on servlet

i have json like
{
"condition": "AND",
"rules": [{
"id": "BirthDate",
"field": "BirthDate",
"type": "date",
"input": "text",
"operator": "equal",
"value": "2016/04/13"
}]}
i just want to iterate it on servlet for that i create
public String getRuleList(){
String ruleList=this.get("rules");
return ruleList;
}
public String getcondition(){
return this.get("condition");
}
as getter setter when i send this json without using JSON.stringify i got the value of condition but unable to fetch rules.By using JSON.stringify i unable to fetch anything. please help..
rules is JSONArray and simple get returns an object. Try to get it with the json libraries custom method.
If you are using org.json try this
this.getJSONArray('rules')
Try to provide some more information such as the json library you are using, the output you got for this.get('rules') and how is this initialized for a much better answer
To solve above problem i do
result =JSON.stringify(result);
var json = JSON.parse(result);
var queryData={
rules:JSON.stringify(json.rules),
condition:JSON.stringify(json.condition)
};
console.log("result"+JSON.stringify(result));
if (!$.isEmptyObject(result)) {
var url = location.protocol + "//" + location.host +appContext+"?command=QueryBuilderServlet&action=getQueryJson";
$.ajax({
url:url,
type: "POST",
data:queryData,
dataType:'json',
});
thanks a lot for your help

Categories