Expected Character for no reason in a JsonPath - java

Assuming that I have this JSON:
{
"response" : {
"code" : "XXX",
"label" : "Lorem Ipsum",
"items" : [
{
"code" : "200",
"label" : "200 !!!"
},
{
"code" : "300",
"label" : "300 !!!!!"
},
{
"code" : "500",
"label" : "+500 !!!!!"
}]
}
}
I want to get the label of the item when code = 500 (as for example) in Java.
I'm using jayWay Library and this jsonPath:
"$.response.items[?(#.code='500')].label"
I'm getting this error while parsing : Expected character: )
The java code :
public static String getElementValueByJsonPath(String jsonContent, String jsonPath) {
if (checkJsonValidity(jsonContent)) {
String returnedValue ="";
Configuration config = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
try {
returnedValue = ""+JsonPath.using(config).parse(jsonContent).read(jsonPath);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return returnedValue;
}
return null;
Anyone knows why I have this error, and can I bypass it with another library or method.
Thanks

You get the error for a very valid reason, that is not a valid jsonpath query.
If you go to https://jsonpath.herokuapp.com/ ( which uses jayway ) and enter the same data and path you will see this is not a valid jsonpath query for jayway, or two of the other implementations, the only one that does not fail outright does not return what you are expecting. I think you need to go back and re-read the jsonpath documentation as this syntax clearly is not valid.
The correct syntax is $.response.items[?(#.code=='500')].label as the documentation clearly states.
I would not rely on implementations that do not fail on incorrect syntax.

Related

Elasticsearch multilevel object search Java

I have a document given below.
{
"my_id": "123",
"content": {
"name": "abc",
"designation": "engineer"
}
}
I have written Java code for elasticsearch to access the field name which is given below.
String field = "content.name";
String value = "abc"
SearchResponse response = esClient.prepareSearch("indexName")
.setTypes("data")
.setQuery(QueryBuilders.matchQuery(field, value))
.get();
But the output that I am getting for this multilevel object search empty hits. Is there a way to access multilevel objects in Java
The given query works from sense.
GET indexName/_search
{
"query" : {
"match" : {
"content.name" : "abc"
}
}
}

How to search for a JSON field in elasticsearch using java?

This is JSON that I want to use for a search:
{
"_index" : "test", "_type" : "insert", "_id" : "3",
"_version" : 2, "found" : true,
"_source" : {
"ACCOUNT_ID" : "123",
"CONTACT_ID" : "ABC"
}
}
How do I search for all the JSON which have ACCOUNT_ID starting from 1?
You can use Wildcard in elasticsearch to search for an ACCOUNT_ID which starts from 1
GET index/_search
{
"query": {
"wildcard": {
"ACCOUNT_ID ": {
"value": "1*"
}
}
}
}
In Java, you can try something like this:
QueryBuilders.wildcardQuery("ACCOUNT_ID ", "1*");
From what i see in your comments you are trying to find id's starting with 1 for example. Well if your analyzer is the standard one the id "123" is tokenized like "123". You can use wildcard and search like '1*'. Be careful using wildcards cause it takes some memory.
See here: QueryString - Wildcard

How to get nested types in Elasticsearch

I have the following document:
{
"_index" : "testdb",
"_type" : "artWork",
"_id" : "0",
"_version" : 4,
"found" : true,
"_source":{"uuid":0,
"StatusHistoryList":[
{
"ArtWorkDate":"2015-08-28T15:52:03.030+05:00",
"ArtworkStatus":"ACTIVE"
},
{
"ArtWorkDate":"2015-08-28T15:52:03.030+05:00",
"ArtworkStatus":"INACTIVE"
}
]
}
and here is the mapping of the document:
{
"testdb" : {
"mappings" : {
"artWork" : {
"properties" : {
"StatusHistoryList" : {
"type" : "nested",
"properties" : {
"ArtWorkDate" : {
"type" : "string",
"store" : true
},
"ArtworkStatus" : {
"type" : "string",
"store" : true
}
}
},
"uuid" : {
"type" : "integer",
"store" : true
}
}
}
}
}
}
Now I want to access the values of StatusHistoryList. I got null values if I do it like this:
val get = client.prepareGet("testdb", "artWork", Id.toString()).setOperationThreaded(false)
.setFields("uuid",,"StatusHistoryList.ArtworkStatus","StatusHistoryList.ArtWorkDate","_source")
.execute()
.actionGet()
var artworkStatusList= get.getField("StatusHistoryList.ArtworkStatus").getValues.toArray()
var artWorkDateList= get.getField("StatusHistoryList.ArtWorkDate").getValues.toArray()
then I got null values from the code but my document contains the values then I found this question
so after that i tried to do it like this
var smap = get.getSource.get("StatusHistoryList").asInstanceOf[Map[String,Object]]
but then a ClassCastException is thrown
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
Please help me how can I get the values of StatusHistoryList 's ArtworkStatus and ArtWorkDate values please guide me I will be very thankfull to you.
You have almost derived the solution. The GET request has retrieved the response but the problem is in parsing the response.
Let's see the problem. Below is the document that the elastic search returns as source
{
"uuid":0,
"StatusHistoryList":[
{
"ArtWorkDate":"2015-08-28T15:52:03.030+05:00",
"ArtworkStatus":"ACTIVE"
},
{
"ArtWorkDate":"2015-08-28T15:52:03.030+05:00",
"ArtworkStatus":"INACTIVE"
}
]
}
When we do get.getSource.get("StatusHistoryList") it returns List ArtWork objects and not a Map. That is the reason for the classCastException exception.
So if you cast the response to list of objects your problem will be solved.
But this would not be an ideal solution. Some of the libraries like Jackson-Faterxml does the job for you. Using the fasterxml library you can bind the json to equivalent POJO Object.

JSON Format Error-Amzon EC2 instance creation

i am doin Amazon Stack Creation through Java Eclipse.
tis below line of code is throwing the error
csr.setTemplateURL("https://s3.amazonaws.com/cloudformation-templates-us-east- 1/AutoScalingMultiAZSample.template");
I am getting the error as :
Caught Exception: Parameters: [KeyName] must have values (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 9363d711-3535-11e4-8cf2-913ef42879cb)
Reponse Status Code: 400
my json template url is
https://s3.amazonaws.com/cloudformation-templates-us-east-1/AutoScalingMultiAZSample.template
Please help on this to detect the exact source of the error.
Ok i tried to validate your json schema using online validator.
http://jsonlint.com/
I just copied your json schema and pasted there. It said invalid schema expecting { on line 1. Ok for sure i have to put opening and closing brackets and in between your schema. But again it gave error. Extra Bracket } on last line. So i had to remove it. And then json schema was validated. It means somewhere in your schema you are putting an extra closing bracket }.
I think the place where you are making mistake is:
"InstanceSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Enable SSH access and HTTP from the load balancer only",
"SecurityGroupIngress" : [ {
"IpProtocol" : "tcp",
"FromPort" : "22",
"ToPort" : "22",
"CidrIp" : { "Ref" : "SSHLocation"}
},
{
"IpProtocol" : "tcp",
"FromPort" : { "Ref" : "WebServerPort" },
"ToPort" : { "Ref" : "WebServerPort" },
"SourceSecurityGroupOwnerId" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.OwnerAlias"]},
"SourceSecurityGroupName" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.GroupName"]}
} ]
}
}//Extra Bracket i think so
},
"Outputs" : {
"URL" : {
"Description" : "The URL of the website",
"Value" : { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]]}
}
}
}

JSON: parsing with java and org.json (recursion)

I'm using the package org.json to parse a JSONArray (I have the json strings saved in a database). However, I don't succeed in parsing it when the same key could have associated a String or a JSONObject, depending on the context.
For example, see the following JSON code...
[ { "cssClass" : "input_text",
"required" : "undefined",
"values" : "First Name"
},
{ "cssClass" : "checkbox",
"required" : "undefined",
"title" : "What's on your pizza?",
"values" : { "2" : { "baseline" : "undefined",
"value" : "Extra Cheese"
},
"3" : { "baseline" : "undefined",
"value" : "Pepperoni"
}
}
}
]
In the code above, the key "values" has 2 possibilities...
A String with value "First Name"
A JSONObject with value {"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"}}.
How am I able to process this correctly when the value could be 2 different data types?
You'll probably still need to detect whether it is a JSONObject or a String, so that you can process it further, but perhaps something here might help...
You could try something like this...
String cssClass = myJson.getString("cssClass");
if (cssClass.equals("input_text")){
// Read it as a String
String values = myJson.getString("values");
}
else if (cssClass.equals("checkbox")){
// Read it as a JSONObject
JSONObject values = myJson.JSONObject("values");
// further processing here
}
Or maybe something like this...
String cssClass = myJson.getString("cssClass");
String values = myJson.getString("values");
if (cssClass.equals("input_text")){
// do nothing - it's already a String
}
else if (cssClass.equals("checkbox")){
// Parse the String into a JSONObject
JSONObject valuesObject = new JSONObject(values);
// further processing here
}
Think it this way in js or java duplicate variable creation under same scope is invalid,so to avoid ambiguity put them in separate json object with different variable names before putting it to the json array.

Categories

Resources