How can i extract jquery parameters from url? - javascript

I need to extract the "data:" for station listed bellow from this url http://swe-sso.dlr.de/Ionospheric_Perturbations/Rate_Of_Change_Of_TEC_Index/mean_ROTI_Europe/latest/mean_ROTI_Europe.json
{
"properties": {
"rcv": "BUCU00ROU0_EUREF",
"sat": "G24",
"roti": 0.508,
"azimuth_deg": 168.4,
"elevation_deg": 20.99
},
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
25.34,
45.15
]
}
}
"Data:" is the main index for stations data
what is the correct syntax to do that with js?

I assume you mean sat and not station, as that doesn't exist in your example. You could access it like this with JavaScript by assigning it to a variable:
var sat = yourJSONobj["properties"]["sat"]
Here's an example printing that object in that array:
yourJSON = { "properties":{ "rcv":"BUCU00ROU0_EUREF", "sat":"G24", "roti":0.508, "azimuth_deg":168.4, "elevation_deg":20.99 } }, { "type":"Feature", "geometry":{ "type":"Point", "coordinates":[ 25.34, 45.15 ] } }
document.getElementById("json").innerHTML +=JSON.stringify(yourJSON["properties"]["sat"]);
<p id="json"></p>
edit: cleaned up code

I'm going to try to point you in the right direction here, but you'll need to still do some reading. To clarify, you appear to be asking how you can use jQuery to load some JSON data, and then pull out parts of it. I'm inferring this by looking at the URL you provided.
First thing you'll want to know is how to get that JSON that's sitting behind the URL into a JavaScript object. You should look at http://api.jquery.com/jQuery.getJSON/ to get started there. That will tell you how to load the JSON.
Next, you appear to want to build a new JavaScript object that has only a small subset of the data in the much larger response. That's pretty much just pulling out the bits by traversing the paths in the returned JSON. In this case though, there's a lot of data, and there's a lot of repetition. If you're looking to grab a specific piece of that data, you can either write some code to loop through elements in one of the arrays that contains the data you want (maybe the metadata.integrated_gnss_stations.features array), or using something like JSONPath (http://jsonpath.com/) to easily traverse into it.
If you use JSONPath, you could use a path like
metadata.integrated_gnss_stations.features..[?(#.rcv=='BUCU00ROU0_EUREF')]
… to get an array of all 5 satellites for the items where rcv == "BUCU00ROU0_EUREF". You can then take that return and project it into whatever other form you'd like.

Related

JSON.parse giving only the last element as output

I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.
I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.
The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total.
I expect all the elements to be assigned to the variable.
request.open('GET', 'http://localhost:3000/listofvoted', true);
request.onload = function () {
console.log(this.response)
console.log(JSON.parse(this.response));
}
request.send();
The JSON I receive:
{
"name": "Bran",
"name": "Ram",
"name": "Sam"
}
Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.
For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.
Here are some alternative ways of representing what you have that may work:
Use an array of discrete objects:
[
{ "name": "Bran" },
{ "name": "Ram" },
{ "name": "Sam }"
]
Use an array of names:
{
"names": [ "Bran", "Ram", "Sam" ]
}
As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.
See also, How to get the JSON with duplicate keys completely in javascript

Pentaho JavaScript JSON - Concatenate json objects into existing JSON document based on keys

Basically what i'm trying to do is to build up a Json document, with it's pieces all spread into smaller Json pieces, all rows containing the Keys needed to insert the smaller Json bits inside the correct json structure.
My problem starts in that i know next to nothing about JavaScript. So i would have to learn JavaScript from scratch(already doing), So i'll describe as best i can the issue and what i want to achieve.
Issues: In every Pentaho / Json post i see a hardcoded(Like This answer, which is helpful but again, hardcoded number of fields) JavaScript to build a pre-formed Json structure, what i need is a way to to insert / create, dynamically built info into a Json Structure. And it also needs Nested Structures.
So, in the start i would bulk build all the Flat Json structure, which can be easily done with the Json output Step, since it outputs built Json objects, the objects themselves can be built dynamically, and then just concatenated(Again i don't know if this is possible).
After the flat part is done, comes the part of concatenating the other objects inside the correct structure, some are just more plain objects, others are Arrays of Objects(Nested part).
This is where i need confirmation from someone who understands this part that it is possible to achieve inside Pentaho JavaScript, or the only way using Pentaho is to build hardcoded structures. Below i'll show in Json examples what i want.
This would be an example of the Flat JSON:
{
"Apolices": [{
"Apolice": {
"APO_numero_apolice": "1321635113",
"APO_ramo": "312",
"APO_data_proposta": "22-05-2018",
"APO_valor_desconto": 0.0,
"APO_valor_liquido": 1550.39,
"APO_cod_parceiro_negocio": "1000",
"APO_inicio_vigencia": "22-05-2018",
"APO_status_apolice": "EMITIDA"
}
},
{
"Apolice": {
"APO_proposta": "3212121",
"APO_data_registro": "08-08-2018",
"APO_numero_apolice": "7891321498",
"APO_ramo": "515",
"APO_data_proposta": "22-03-2018",
"APO_valor_desconto": 0.0,
"APO_valor_liquido": 2150.72,
"APO_cod_parceiro_negocio": "7548151100",
"APO_inicio_vigencia": "22-07-2018",
"APO_status_apolice": "EMITIDA",
"APO_produto": null,
"APO_codigo_corretor": "812182",
"APO_fim_vigencia": "22-05-2019",
"APO_valor_bruto": 2320.8,
"APO_percentual_comissao": 19,
"APO_iof": null
}
}
]
}
Then in the course of said implementation, the desired outcome would be something like :
{
"Apolices": [{
"Apolice": {
"APO_numero_apolice": "1321635113",
"APO_ramo": "312",
"APO_data_proposta": "22-05-2018",
"APO_valor_desconto": 0.0,
"APO_valor_liquido": 1550.39,
"APO_cod_parceiro_negocio": "1000",
"APO_inicio_vigencia": "22-05-2018",
"APO_status_apolice": "EMITIDA"
},
"Item": {
"ITE_ano_fabricacao": "2001",
"ITE_modelo": "FOCUS SEDAN GHIA 2.0 MPI 16V 4P",
"ITE_ano_modelo": "2001",
"Cobertura": [{
"COB_cod_cobertura": "21",
"COB_valor_importancia": "50000",
"COB_valor_premio": "415,71",
"COB_cobertura": "RCF-V - Danos Materiais"
},
{
"COB_cod_cobertura": "17",
"COB_valor_importancia": "16712",
"COB_valor_premio": "1165,96",
"COB_cobertura": "Colisão,Incêndio e Roubo\/Furto"
}
]
}
},
{
"Apolice": {
"APO_proposta": "3212121",
"APO_data_registro": "08-08-2018",
"APO_numero_apolice": "7891321498",
"APO_ramo": "515",
"APO_data_proposta": "22-03-2018",
"APO_valor_desconto": 0.0,
"APO_valor_liquido": 2150.72,
"APO_cod_parceiro_negocio": "7548151100",
"APO_inicio_vigencia": "22-07-2018",
"APO_status_apolice": "EMITIDA",
"APO_produto": null,
"APO_codigo_corretor": "812182",
"APO_fim_vigencia": "22-05-2019",
"APO_valor_bruto": 2320.8,
"APO_percentual_comissao": 19,
"APO_iof": null
}
}
]
}
The Json Objects of "Item" and "Cobertura", and others, would come as already built Json objects, with the necessary keys to insert the entire object in the correct position of the structure.
I have done next to no coding myself as of yet since i'm still learning JavaScript, but i already know that Pentaho's JavaScript is somewhat limited in resources, that's why i'm asking ahead if this is even possible inside Pentaho/Kettle
Don't be afraid of the resource limitations for Javascript in PDI. It uses the official Rhino OpenSource project which is 100% ES6 compatible.
Of course, the dynamic nature of JS makes it a little bit slower, but I do not think the difference will be significant unless you have a continuous input flow of millions per minutes.

Working with 2D array in D3

I'd like to visualize data pulled in from the census data API, specifically from the ACS survey.
The data is returned in a non-standard version of JSON, as a two-dimensional array. It basically looks like this:
[
[
“POPULATION”,
“DATE”,
“ANOTHERTHING”
],
[
“ALABAMA”,
“2000”,
“MORESTUFF”
],
[
“ALASKA”,
“2000”,
“OTHERSTUFF”
],
…
]
I'm unfamiliar with working with this kind of JSON data, which almost looks more like a CSV, where the keys are written in the first line, and the values in every line after the first.
Is anyone familiar with how to parse and work with this data in D3, without having to go convert it first (i.e. https://gist.github.com/sarfarazansari/7e8ae05168b80b36016eb1c561a82f73)? (I'd like to draw from the data API directly).
Any help or guidance would be much appreciated.
First of all: do not use smart quotes (“) in a JSON (or in your code, whatever it is). I reckon that your real JSON is correct, this just happened because you used a text editor, like MS Word, to write this question. Also, there is no such a thing like non-standard JSON, because there is no standard JSON to begin with. You just have a JSON which is an array of arrays, nothing special here.
That being said, you can use that exact data structure to create your charts... However, specially if you're a beginner, it's a good idea to stick with the most common (here we can say standard) way to organise the data in D3 codes, which is an array of objects.
We can easily convert that array of arrays in an array of objects, which will be more comfortable to you.
First, supposing that your array is named data, let's extract the headers:
var keys = data.shift();
That not only creates a headers array, but it will remove the first inner array from the data array.
Now, we iterate over each inner array, creating an object with all the key/value pairs we need:
var newData = data.map(function(d) {
var obj = {};
d.forEach(function(e, i) {
obj[keys[i]] = e;
});
return obj;
});
There are shorter ways to do this, the one above is quite verbose but it is more didactic.
Here is a demo using the data you shared:
var data = [
[
"POPULATION",
"DATE",
"ANOTHERTHING"
],
[
"ALABAMA",
"2000",
"MORESTUFF"
],
[
"ALASKA",
"2000",
"OTHERSTUFF"
]
];
var keys = data.shift();
var newData = data.map(function(d) {
var obj = {};
d.forEach(function(e, i) {
obj[keys[i]] = e;
});
return obj;
});
console.log(newData)
<script src="https://d3js.org/d3.v5.min.js"></script>

Correct layout for Json data when searching different attributes

I have created a data file using JSON. The data is a selection of variables about tube stations. See below for a section of the file.
This setup works very well for finding stations when you have the station id.
example: when you click on a station on my webpage the elements id is the station code and this allows a popup box to be filled with the stations name and zone.
However, how would it be best to find the location of the station when for example given the full text name?
a) I would have to have a code iterating through every station object and using an if command check the name in the object against the name given.
b) created a set of key:value pairs in a second javascript object which is first used to lookup the station id then searches in the first object for the rest of the station data.
Also how would I find data on all the stations on a given line.
a) iterate through and check for each that the tubelines array contains the line string
b) Yet another object containing all station codes under a line heading.
{
"BST": {
"name": "Baker Street",
"Location": [
51.523129639184,
-0.15688978273689
],
"zone": 1,
"tubelines": [
"Bakerloo",
"Circle",
"Hammersmith & City",
"District"
],
"Bakerloo": {
"stepfreetrain": false
},
"Circle": {
"stepfreetrain": false
},
"Hammersmith & City": {
"stepfreetrain": false
},
"District": {
"stepfreetrain": false
}
},
"CHX": {
"name": "Charing Cross",
"Location": [
51.508358644804,
-0.12478853109718
],
"zone": 1,
"tubelines": [
"Bakerloo",
"Northern"
],
"Bakerloo": {
"stepfreetrain": true
},
"Northern": {
"stepfreetrain": true
}
}
}
So the key question is, is this the best way to lay out the data above and if so which is the quickest method to pull out information?
To answer your question (was too long to post it as comment):
Create these secondary objects within your "initialization" phase. After generating the objects you can make them accessible via a simple "API". Made a small example (using jQuery and assuming your spots are stored in a spots.json file):
var myApp = {
init: function() {
// show loading screen while fetching data and creating the "lookup" objects
showLoader();
var loadSpots = $.ajax({
url: "/spots.json"
});
loadSpots.done(function(spots) {
myApp.spots = spots;
$.each(spots, function(code, details) {
nameLookup[details.name] = spots[code];
});
// All done, hide the loading screen
hideLoader();
});
},
spots: {},
nameLookup: {},
findByCode: function(code) {
return myApp.spots[code];
},
findByName: function(name) {
return myApp.nameLookup[name];
}
};
myApp.init();
// you can then use these API methods to find all information for Baker Street either by name or by code (or by whatever)
myApp.findByCode('BST');
myApp.findByName('Baker Street');
Iterating through one only object: slower
Creating multiple objects with different layouts: redundancy (thus possibly error-prone)
If speed of reading the data is more important than high(er) memory consumption write a function to generate several objects designed for your needs at runtime automatically, ONCE. Don't do that manually since it's error-prone and a monkey task. And don't forget to observe changes to your main object (if it can be modified at runtime) so you can regenerate your optimized objects as soon as an entry gets modified. That costs some performance once when starting your application but then you can read from the generated objects fast and easily.
If low memory consumption is more important than speed of finding entries (for example because your application is running on older devices with low memory) just iterate through the entries. I'm not 100% sure if one iteration per lookup uses less memory than creating several different objects and keeping them in memory - it probably depends on the size of your data object.
Looking up keys on the first level of an object is of course always faster than iterating and searching for values deep within an object but it uses more memory since the additional objects must be stored somewhere.
I would suggest to put the data of all the separate tube lines inside the "tubelines" property.
For example:
{
"tubelines": {
"Bakerloo": {
"stepfreetrain": true
},
"Northern": {
"stepfreetrain": true
}
}
}
That makes looking up data easier as you can traverse the JSON "tree" for each tube line and find it's data.
Also, I find it easier to name the coordinates "lat" and "long" as separate properties of "Location" (Location.lat, Location.long) vs using an array (Location[0], Location[1]) for readability and eliminating possibility of making mistakes when entering data.
I would suspect that given the number of tube stations (270?) that you're not going to notice any particular data arrangement being superior. A simple iteration would be barely noticeable on virtually any platform.
I would rather (as ever) concentrate on making the code legible and easy to manage/maintain, and worry about specific performance issues as they arise.

How to retrieve data from json output

I have a json output that looks like this.
{
"38467": {
"name": "Tony Parker",
"book": [
{
"title": {
"name": "MediaWorks"
},
},
],
}
"59678": {
"name": "Ray Thomas",
}
}
Actually json output is a lot bigger list. But I want to only save author's name and their publisher. I want save multiple individual records for a single model.
I am using jquery to assign input elements their values.
$('#Author' + i + 'Title').val(response...);
But it is not working.
I appreciate any help.
Thanks.
JSON is just javascript data - a javascript object. Assign the "decoded" JSON data to a variable (say var dat), then you can access members the normal object/array away: dat[38467]['name'] is Tony Parker and so on.
comment update:
once you've decoded/stored the data, you can use a regular javascript foreach loop to go over it:
for (var bookID in booklist) {
var author = booklist[bookID]['name'];
var title = booklist[bookID]['book'][0]['title']['name'];
// ...do stuff here...
}
There's nothing magical about JSON, it's just javascript data packed up for easy/clean transmission. Of course, if you're using a framework such as jQuery or MooTools, you'd be better off using their own .each() operators, otherwise you'll get various bits of useless fluff from the for() loop.
edit: fixed code sample as per marimuthu's comment (good catch, thanks).

Categories

Resources