Converting non-JSON text string into JSON object - json

I have this simple string repeated 1000's of times for worldwide weather widget I'm using in a large text file:
City Name = "Albuquerque, NM, US" Location = "NAM|US|NM|ALBUQUERQUE" Country = "United States"
Notice how it's formatted.
CITY NAME
LOCATION
COUNTRY
The string I'm actually passing into the Widget is the LOCATION string: "NAM|US|NM|ALBUQUERQUE"
So what I'm trying to do is convert the first example of the CITY NAME, LOCATION and COUNTRY into a JSON OBJECT.
Then, once I have that, I wish to allow the user to INPUT their current location or any location for that matter thereby passing the user input into this:
$('#digiclock').jdigiclock({
// Configuration goes here
clockImagesPath: "images/clock/",
weatherImagesPath: "images/weather/",
am_pm: false,
weatherLocationCode: "NAM|US|TN|CHATTANOOGA",
weatherMetric: "F",
weatherUpdate: "5",
proxyType: "php"
});
The weatherLocationCode is actually the LOCATION in the string above. So when the user inputs their CITY/STATE or just CITY, I want to parse the newly formed JSON object from the above text, capture the location, and stick-it up in the function.
This is what the end result should be:
// JSON OBJECT
{data : [
{
"City Name" : "Aachen, DE",
"Location" : "EUR|DE|GM011|AACHEN",
"Country" : "Germany"
}
]
}
Simple? Not so much.

Related

How to differentiate the explicitly assigning null to the field or field that is not in the json file for #PATCH

I am using #PATCH for the partial update of the record.
My table is emp:
empId - Int
lastName -String
firstName - String
city - String
desc - String
Patch json file for emp/1:
{"city" : "NULL", "lastName": "newLastName"}
How can I pass this to the pl/sql procedure (how the sql query can be constructed only to update city and lastName) and how to differentiate between explicity city set to NULL and desc is not found in json.
There are multiple ways on how to deal with that kind of situation, I implemented at least two different ones:
Send a JSON document that represents the updated resource
Either you require the client to always send the complete JSON document (not a partial one) so you always get all values in a single request (easy). Absent values mean that the field is supposed to be null.
Or you allow the client to send a partial JSON document but then you need a unique identifier to distinguish between an absent field (not to touch) and a field that needs to be overridden with null (harder but not impossible).
Send a JSON document that contains operations on a resource, e. g. { "operation": "update", "field": "city", "value": "New City" } which replaces the old value of city with New City or { "operation": "delete", "field": "description" } which deletes description (requires parsing patches differently).

How do I concatenate a dynamic string value using Groovy to JSON response after it's parsed to get a specific node value in JSON

slurperresponse = new JsonSlurper().parseText(responseContent)
log.info (slurperresponse.WorkItems[0].WorkItemExternalId)
The above code helps me get the node value "WorkItems[0].WorkItemExternalId" using Groovy. Below is the response.
{
"TotalRecordCount": 1,
"TotalPageCount": 1,
"CurrentPage": 1,
"BatchSize": 10,
"WorkItems": [ {
"WorkItemUId": "4336c111-7cd6-4938-835c-3ddc89961232",
"WorkItemId": "20740900",
"StackRank": "0",
"WorkItemTypeUId": "00020040-0200-0010-0040-000000000000",
"WorkItemExternalId": "79853"
}
I need to append the string "WorkItems[0].WorkItemExternalId" (being read from a excel file) and multiple other such nodes dynamically to "slurperresponse" to get the value of nodes rather than directly hard coding as slurperresponse.WorkItems[0].WorkItemExternalId..
Tried append and "+" operator but i get a compilation error. What other way can I do this?
slurperrsesponse is an object its not a string that's why the concatenation does not work
Json Slurper creates an object out of the input string. This object is dynamic by nature, you can access it, you can add fields to it or alter the existing fields. Contatenation won't work here.
Here is an example:
import groovy.json.*
​def text = '{"total" : 2, "students" : [{"name": "John", "age" : 20}, {"name": "Alice", "age" : 21}] }'
def json = new JsonSlurper().parseText(text)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
json.total = 3 // alter the value of the existing field
json.city = 'LA' // add a totally new field
json.students[0].age++ // change the field in a list
println json​
This yields the output:
[total:3, students:[[name:John, age:21], [name:Alice, age:21]], city:LA]
Now if I've got you right you want to add a new student dynamically and the input is a text that you've read from Excel. So here is the example:
json.students << new JsonSlurper().parseText('{"name" : "Tom", "age" : 25}')
// now there are 3 students in the list
Update
Its also possible to get the values without 'hardcoding' the property name:
// option 1
println json.city // prints 'LA'
// option 2
println json.get('city') // prints 'LA' but here 'city' can be a variable
// option 3
println json['city'] // the same as option 2

How do I access this JSON API data in Ruby?

I am writing a short Ruby program that is going to take a zipcode and return the names of cities within 2 miles of that zipcode. I successfully called an API and was able to parse the JSON data, but I'm unsure how to access the 'city' key.
url = API call (not going to replicate here since it requires a key)
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
Here's what my JSON looks like.
{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}
I've been trying to access 'city' like this:
response['result'][0]['city']
This appears to be incorrect. Also tried
response[0][0]['city']
And a couple of other permutations of the same code.
How can I get the value 'Northfield' out of the JSON data?
You're almost there, just use results instead of result on the result of JSON.parse(response) instead of on response:
JSON.parse(response)["results"][0]["city"]
#=> "Northfield"
JSON parse will create a hash then you can target the results which is an array of hashes, like so:
hash = JSON.parse(response)
hash['results'].select{|h| h['city'] == 'Northfield'}
Or if you only care about the results:
array = JSON.parse(response)['results']
array.select{|a| a['city' == 'Northfield'} #
To get just a single data point from the data, you might select one item in the array and then the key of the value you want:
array[0]['city']
For all the cities
cities = array.map{|k,v| k['city']}
You have a typo error, instead of response['result'] you can use it like response[:results].
And if you want to get the value of city key from all the hash, then response['result'][0]['city'] will not work.
After parsing response you will get an array of hashes, i.e
[{:zip=>"08225", :city=>"Northfield", :county=>"Atlantic", :state=>"NJ", :distance=>"0.0"}, {:zip=>"08221", :city=>"Linwood", :county=>"Atlantic", :state=>"NJ", :distance=>"1.8"}]
And if you want to fetch the values of key city from all the hash then you can try this steps
response[:results].map{|x| x[:city]}
which will give the result
["Atlantic", "Atlantic"]

How to fill in several dropdowns subsequently from JSON in Elm?

We are stuck with filling in form from JSON data and need help. The component is about selecting the ward in the district of the given city.
The data structure is a tree of Cities, Districts, and Wards with approximately following structure (everything is wrapped in GeoJSON):
// Cities: '/api/cities/berlin'
{
features: [
{
type: "Feature",
properties: {
slug: "berlin",
name: "Berlin",
districts: [
{name: "Neukölln", slug: "neukolln", ...}
]
},
geometries: {...}
}
]
}
// Districts: '/api/cities/berlin/districts/neukolln'
{
features: [
{
type: "Feature",
properties: {
slug: "neukolln",
name: "Neukölln",
wards: [
{name: "Britz", slug: "britz", ...}
]
},
geometries: {...}
}
]
}
// Wards: '/api/cities/berlin/districts/neukolln/wards'
{
features: [
{
type: "Feature",
properties: {
slug: "britz",
name: "Britz",
},
geometries: {...}
}
]
}
In the view, three are three dropdown boxes for selecting City, District and Ward, thus, when User select City, then District dropdown is filled from the properties.districts field of the JSON response.
Same is applied for the Districts dropdown: wards are filled in from the properties.wards
When the page is loaded it already has an injected JSON of all available Cities (and, accordingly their districts)
What strategy would you advise on:
1) how to get currently selected city and hit server for next administrative divisions? I.e. when a user selects District, get its slug and query server for the wards?
2) how to fill subsequent select from the response or injected JSON on the page? I.e. when user select another City, fill District select box with respective Districts?
Here's how I have done something similar in the past (in elm v0.17.0):
dropdown : List City -> Html Msg
dropdown cities =
div []
[ div []
[ span [] [ text "dropdown label name" ]
, selectOptions cities
]
]
selectOptions : List City -> Html Msg
selectOptions cities =
select [ on "change" ( Json.map (\city -> GetDistrictsMsg city) targetValue ) ]
(List.map setOption cities)
setOption : City -> Html Msg
setOption city =
option [ value city.name ]
[ text city.name ]
And you will repeat the same for districts to get wards.
Start-up
If selected city is known, before the start-up, you can pass in as a flag to Html.App.programWithFlags
The same thing you can do to the list of cities.
Please see the http example, it covers most of the stuff.
If you want to send xhr request on start-up, you might use a little neat trick for that:
init : String -> (Model, Cmd Msg)
init topic =
( Model topic "waiting.gif"
, getRandomGif topic
)
Where getRandomGif will execute the xhr request on start-up, assuming that you have gotten some data for that from passing them as flags or from user input.
On every FetchSucceed, you should send the next xhr to grab the data for the next step.
The flow
Please consider this flow chart, illustrating the flow of your multi step form. Dashed arrows point to steps, where you can restart the cycle, if you want to change the city/district at some point.
Caching layer is optional, Elm offers a variety of data structures for that.

How do I parse a JSON file to bind data to a d3 choropleth map

I'm trying to take data in from a JSON file and link it to my geoJSON file to create a choropleth map with the county colours bound to the "amount" value but also I would like a corresponding "comment" value to be bound to a div for when I mouseover that county.
My code at http://bl.ocks.org/eoiny/6244102 will work to generate a choropleth map when my counties.json data is in the form:
"Carlow":3,"Cavan":4,"Clare":5,"Cork":3,
But things get tricky when I try to use the following form:
{
"id":"Carlow",
"amount":11,
"comment":"The figures for Carlow show a something." },
I can't get my head around how join the "id": "Carlow" from counties.json and "id": "Carlow" path created from ireland.json, while at the same time to have access to the other values in counties.json i.e. "amount" and "comment".
Apologies for my inarticulate question but if anyone could point me to an example or reference I could look up that would be great.
I would preprocess the data when it's loaded to make lookup easier in your quantize function. Basically, replace this: data = json; with this:
data = json.reduce(function(result, county) {
result[county.id] = county;
return result;
}, {});
and then in your quantize function, you get at the amounts like this:
function quantize(d) {
return "q" + Math.min(8, ~~(data[d.id].amount * 9 / 12)) + "-9";
}
What the preprocessing does is turn this array (easily accessed by index):
[{id: 'xyz', ...}, {id: 'pdq', ...}, ...]
into this object with county keys (easily accessed by county id):
{'xyz': {id: 'xyz', ...}, 'pdq': {id: 'pdq', ...}, ...}
Here's the working gist: http://bl.ocks.org/rwaldin/6244803