java jsonxpth parsing json jumping to node - java

I have the following data and i am using "http://commons.apache.org/jxpath/" i want to directly read the coordinates: [51.464426 -0.382974] which is lat,lng how can i read this any quick example i search around and found there is another jsonpath as well is jsonxpath going to work for me any quick solution ?
{
authenticationResultCode: "ValidCredentials"
brandLogoUri: http://dev.virtualearth.net/Branding/logo_powered_by.png
copyright: "Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation."
-
resourceSets: [
-
{
estimatedTotal: 1
-
resources: [
-
{
__type: "Location:http://schemas.microsoft.com/search/local/ws/rest/v1"
-
bbox: [
51.46056328242933
-0.39124021297987016
51.46828871757068
-0.3747077870201298
]
name: "TW4 5AP, Hounslow, United Kingdom"
-
point: {
type: "Point"
-
coordinates: [
51.464426
-0.382974
]
}
-
address: {
adminDistrict: "England"
adminDistrict2: "Hounslow"
countryRegion: "United Kingdom"
formattedAddress: "TW4 5AP, Hounslow, United Kingdom"
postalCode: "TW4 5AP"
}
confidence: "High"
entityType: "Postcode1"
}
]
}
]
statusCode: 200
statusDescription: "OK"
traceId: "16c9b05027c4486fa3adab793cfdb97e|EWRM001665|02.00.82.2800|EWRMSNVM001812, EWRMSNVM001724"
}

https://github.com/jayway/JsonPath/tree/master/json-path or http://code.google.com/p/json-path/. I dont

Related

mongo-java-driver update each item of array field belonging to document applying some conditional logic

I'm working on an event collection, where each document is modeled like so:
{
"event_name": "John Doe Concert",
"event_date": "2022-01-01"
"ticket_types": [
{
"name": "Front seats",
"total": 50 (we'll call this `oldTotal1`),
"available": 25 (we'll call this `oldAvailable1`)
},
{
"name": "Back seats",
"total": 100 (we'll call this `oldTotal2`),
"available": 50 (we'll call this `oldAvailable2`)
}
]
}
Suppose I have a REST API supporting a PUT endpoint which accepts a payload like this:
{
"event_name": "Jane Doe Concert",
"event_date": "2022-02-02"
"ticket_types": [
{
"name": "Front seats",
"total": 100 (we'll call this `newTotal1`),
},
{
"name": "Back seats",
"total": 150 (we'll call this `newTotal2`),
}
]
}
As you can see, I'm looking to update the document (doesn't matter if it's update or replace as long as the operation is atomic on a document level). For each element i in the ticket_types array in the payload, we can assume newTotal[i] >= oldTotal[i]
The way I'd like my document to look like after the update:
{
"event_name": "Jane Doe Concert",
"event_date": "2022-02-02"
"ticket_types": [
{
"name": "Front seats",
"total": 100 (the value of `newTotal1`),
"available": 75 (the value of `oldAvailable1` + `newTotal1` - `oldTotal1`)
},
{
"name": "Back seats",
"total": 150 (the value of `newTotal2`),
"available": 100 (the value of `oldAvailable2` + `newTotal2` - `oldTotal2`)
}
]
}
The problem I'm having is that I would like to perform the calculations of the resulting values of total and available exclusively through Mongo's findAndUpdate operation (without fetching the document first and doing the changes via Java code after so to speak). This is because the environment the code is run in is AWS Lambda, so I don't think I can rely on any locking mechanism other than the DB's own mechanisms, nor would I want to touch MongoDB's Transaction API.
My attempt so far:
final Document result = collection.findOneAndUpdate(query, Updates.combine(
Updates.set("event_name", request.getEventName()),
Updates.set("event_date", request.getDate().toString()),
// please help me!
Updates.set("ticket_types.$[elem].total", ...)
Updates.set("ticket_types.$[elem].available", ...)
Javascript equivalent should be:
db.getCollection("events").updateOne({name: 'John Doe Concert'},
{
$set: {
"ticket_types.$[first].total": 1000,
"ticket_types.$[first].available": "ticket_types.$[first].available" + 1000 - "ticket_types.$[first].total",
"ticket_types.$[second].total": 2000,
"ticket_types.$[second].available": "ticket_types.$[second].available" + 2000 - "ticket_types.$[second].total"
}
},
{
arrayFilters: [
{ "first.name": "Front seats" },
{ "second.name": "Back seats" }
]
}
)
Edit: The goal is to update the data doing calculation using existing attributes. I feel it's possible to achieve this using an update aggregation pipeline.
I am using DocumentDB 4.0 with application layer written in Java
Thanks

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..

ST3 Can't write dot ["."] while "Java syntax" is on

I am using Sublime Text 3 and I can't (that means when I press the key nothing happens) . while I have active java syntax. When I switch to another syntax (f.e. Javascript) problem is gone. Do anyone solved had/solved this problem?
[Installed packages]
{
"installed_packages":
[
"AngularJS",
"Better JavaScript",
"Display Functions (Java)",
"DocBlockr",
"EditorConfig",
"Emmet",
"Format SQL",
"Git",
"Goto Documentation",
"Grunt",
"HexViewer",
"HTML Boilerplate",
"HTML5",
"JavaPropertiesEditor",
"Javascript Beautify",
"jQuery",
"JsFormat",
"LESS",
"LineEndings",
"MoveTab",
"Nette",
"Nunjucks Syntax",
"Package Control",
"PHP Namespace Command",
"PHP-Twig",
"Phpcs",
"PhpDoc",
"Quick File Move",
"SideBarEnhancements",
"SJSON",
"SublimeLinter",
"SublimeLinter-csslint",
"SublimeLinter-html-tidy",
"SublimeLinter-jshint",
"SublimeLinter-json",
"SublimeLinter-php",
"Theme - Phoenix",
"VCS Gutter",
"WordCount"
]
}
[User settings]
{
"color_scheme": "Packages/User/Monokai (SL).tmTheme",
"default_line_endings": "unix",
"detect_slow_plugins": false,
"draw_white_space": "selection",
"ensure_newline_at_eof_on_save": true,
"font_face": "Consolas",
"font_size": 10,
"highlight_line": true,
"ignored_packages":
[
"JavaScript",
"Vintage",
"tern_for_sublime"
],
"show_encoding": true,
"show_line_endings": true,
"translate_tabs_to_spaces": true
}
According to sergioFC comment I did sublime.log_commands(True) and it showed up that package Display Functions (Java) is "blocking" the . key. Disabling the package solved my problem.

creating JSON format output [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write a program which can create an output in JSON format, how would be best way of doing this? and programming languages?
This is an example output of JSON (expected output) which I need to input in the Name, Gender, Qualification and other attributes in a user friendly way during the execution of script. And in which outputs in following JSON format. Sorry, I am new in programming, but so much interested to learn Perl (or) Python (or) Java. What could be the best here?
Any suggestions?
P.S Sorry I am quite new to JSON as well, please apologize me for this basic one.
[
{
"Name":"Steven Mark",
"gender":"male",
"Qualification": {
"college":"Bachelor in Science",
"tech":"certified pro"
},
"contributions": [
{
"name":"biography",
"type":"book",
},
]
},
{
"Name":"Andrea Mark",
"Gender":"female",
"Qualifications": {
"college":"Bachelor in physics",
},
"contributions": [
{
"name":"my insights",
"type":"movie",
},
]
}
]
Virtually every language has a JSON library, including Perl.
use JSON;
my $data = [
{
"Name" => "Steven Mark",
"gender" => "male",
"Qualification" => {
"college" => "Bachelor in Science",
"tech" => "certified pro"
},
"contributions" => [
{
"name" => "biography",
"type" => "book",
},
]
},
{
"Name" => "Andrea Mark",
"Gender" => "female",
"Qualifications" => {
"college" => "Bachelor in physics",
},
"contributions" => [
{
"name" => "my insights",
"type" => "movie",
},
]
}
];
print(encode_json($data));
If you agree to use ANY programming language, i can suggest python. With its json lib you can do following (lines with # is comments):
# import lib
import json
# fill data into variable (this is list with dict objects inside):
data = [{"name":"john"},{"name": "bill"}]
# dump json
json.dumps(data)
Which will output your data as json.
You can start writing python using something from https://wiki.python.org/moin/BeginnersGuide
If you are going to use Python, you can try to use simplejson or json module to create a json object.
For example,
try:
import simplejson
except:
import json
data = dict(a=1,b=2)
with open("results.json", "w") as fp:
json.dump(data, fp, indent=3, encoding="utf-8")
For dumping, json is faster than simplejson (but not by an order of magnitude). For loading, simplejson is faster (but not by an order of magnitude).
You can check here for more detailed comparison between simplejson and json.

What is the best way to get longitude and latitude for an address via Google in java

I'm trying to write some java codes getting locations from address. (not in android environment.)
If possible, I want it to be permanent way as long as Google provides geo-location services in somehow.
I think I cannot say Google javascript geolocation apis uses permanent URL to do that, since the api's Object is to come from Google server at runtime.
However I think it seems to be possible that Android might use a permanent URL to do that since Google is not able to change every device's URLs through which devices get the geolocation services.
Am I wrong?
Is there any addressed Google policy concerning it?
Thanks in advance.
You may try to use the Google HTTP APIs for getting geocoding and reverse-geocoding.
Geocoding Requests
A Geocoding API request must be of the following form:
http://maps.googleapis.com/maps/api/geocode/output?parameters
where output may be either of the following values:
json (recommended) indicates output in JavaScript Object Notation (JSON)
xml indicates output as XML
Follow this link for more:https://developers.google.com/maps/documentation/geocoding/
If you are thinking to use Google GeoCoding then this stuff will be useful to you :
A Geocoding API request must be of the following form:
http://maps.googleapis.com/maps/api/geocode/output?parameters
where output may be either of the following values:
json (recommended) indicates output in JavaScript Object Notation (JSON)
xml indicates output as XML
To access the Geocoding API over HTTPS, use:
https://maps.googleapis.com/maps/api/geocode/output?parameters
HTTPS is recommended for applications that include sensitive user data, such as a user's location, in requests.
In either case, certain parameters are required while some are optional. As is standard in URLs, all parameters are separated using the ampersand (&) character. The list of parameters and their possible values are enumerated below.
Required parameters
address — The address that you want to geocode.
or
latlng — The textual latitude/longitude value for which you wish to obtain the closest, human-readable address. See Reverse Geocoding for more information.
or
components — A component filter for which you wish to obtain a geocode. See Component Filtering for more information. The components filter will also be accepted as an optional parameter if an address is provided.
sensor — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false.
Maps API for Business users must include valid client and signature parameters with their Geocoding requests. Please refer to Maps API for Business Web Services for more information.
Optional parameters
bounds — The bounding box of the viewport within which to bias geocode results more prominently. This parameter will only influence, not fully restrict, results from the geocoder. (For more information see Viewport Biasing below.)
language — The language in which to return results. See the list of supported domain languages. Note that we often update supported languages so this list may not be exhaustive. If language is not supplied, the geocoder will attempt to use the native language of the domain from which the request is sent wherever possible.
region — The region code, specified as a ccTLD ("top-level domain") two-character value. This parameter will only influence, not fully restrict, results from the geocoder. (For more information see Region Biasing below.)
components — The component filters, separated by a pipe (|). Each component filter consists of a component:value pair and will fully restrict the results from the geocoder. For more information see Component Filtering, below.
JSON Output Formats
In this example, the Geocoding API requests a json response for a query on "1600 Amphitheatre Parkway, Mountain View, CA":
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
We've left the sensor parameter in this example as a variable true_or_false to emphasize that you must set this value to either true or false explicitly.
The JSON returned by this request is shown below. Note that actual JSON may contain less whitespace. You should not make assumptions about the amount or format of whitespace between requests.
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara",
"short_name" : "Santa Clara",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.42291810,
"lng" : -122.08542120
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.42426708029149,
"lng" : -122.0840722197085
},
"southwest" : {
"lat" : 37.42156911970850,
"lng" : -122.0867701802915
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Here is some sample code that will help you to grab the latitude and longitude :
public static void main(String[] args) {
try
{
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false");
URLConnection conn = url.openConnection();
conn.connect();
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
StringBuffer sbLocation = new StringBuffer();
for (int i=0; i != -1; i = isr.read())
{
sbLocation.append((char)i);
}
String getContent = sbLocation.toString().trim();
if(getContent.contains("results"))
{
String temp = getContent.substring(getContent.indexOf("["));
JSONArray JSONArrayForAll = new JSONArray(temp);
String lng = JSONArrayForAll.getJSONObject(0).getJSONObject("geometry").getJSONObject("location").get("lng").toString();
String lat = JSONArrayForAll.getJSONObject(0).getJSONObject("geometry").getJSONObject("location").get("lat").toString();
System.out.println(" Latitude : " + lat);
System.out.println(" Longitude : " + lng);
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

Categories