Trying to parse special characters to retrieve JSON element in JavaScript - javascript

I need help on a university project I am working on with NodeRed. I am integrating a JSON API in JS (NodeRed) and hit a roadblock. Here's the kind of JSON I'm retrieving:
{"#SpeciesCode":"NO2","#MeasurementDateGMT":"2016-04-04 00:00:00","#Value":"58.2"}
That "#" sign is really giving me all sorts of troubles because wether I use JSON.parse or stringify or escaping, it is either telling me " Unexpected token #" or just "undefined value".
Here is the code I'm working with:
var body = msg.payload;
var bodyParsed = JSON.parse(body);
var data = bodyParsed.AirQualityData.Data;
var valueStr="#Value";
var value=JSON.stringify(valueStr);
var valueParsed=JSON.parse(value);
var element = data[0].valueParsed;
return {payload:element};
If you want to have a go at it, here's the URL to the data: http://api.erg.kcl.ac.uk/AirQuality/Data/Site/SiteCode=WM6/StartDate=2016-04-04/EndDate=2016-05-04/Json
[UPDATE: SOLVED] Thanks to jcubic who provided the solution in the comments below:
to access property using a variable you need to use bracket notation:
var element = data[0][valueParsed]; also you don't need to stringify and parse #value just use data[0]["#Value"]
So the new code is
var body = msg.payload;
var bodyParsed = JSON.parse(body);
var data = bodyParsed.AirQualityData.Data;
var element = data[0]["#Value"];
return {payload:element};

Related

How to read a parameter with a period using Express in Node JS?

My macro is called from a url containing parameters like:
?title=TitleHere&macro.id=a1
I'm finding it easy to pick up the title, but I am getting an error when trying to get the macro.id parameter as follows.
var requestTitle = req.query.title;
var requestMacroId = req.query.macro.id;
What is the correct way to get a parameter with a period in the name?
Try
var requestTitle = req.query['title'];
var requestMacroId = req.query['macro.id'];

How do I pass a Java Map<Long, Integer> into scala-play?

In my play framework project I have a confirmed functional Java map of the form Java that is passed to a html page home.scala.html
The map variable is passed in as other (working) variables are, at the top of the page:
#(workingVar1: String, workingVar2: Int, mapVar: Map[Long, Integer])
But developer tools in google chrome highlights this part of the javascript (embedded in home.scala.html's head):
var myMap = #mapVar;
With the error Uncaught SyntaxError: Unexpected token =
So none of the javascript works. What is the correct way to pass this map in?
You can use Java/Scala variables in Twirl Scala templates and both are executed on the server side.
Now on server side Twirl engine translates Java object to something (which probably isn't what you want) and in this form is passed to client, and then this JavaScript is executed.
You want to make sure that client will receive valid JavaScript code.
To assign proper value, you will have to mix some JSON libraries, which will help you assign value in a proper way.
Eg. on the controller side:
...
Map<Long, Integer> map = new HashMap<>();
map.put(1L, 2);
map.put(3L, 3);
String yourMap = Json.stringify(Json.toJson(map));
Now you want to pass yourMap to view, and then you will assign to myMap
using #Html as we want it as raw content fragment:
#(workingVar1: String, workingVar2: Int, mapVar: String)
var myMap = #Html(mapVar);
Try and let me know if it helped.
An inelegant but functional solution is as follows:
Bring in the Java Map as a string:
var stringMap = "#mapVar";
Removes the braces and spaces inserted into the string unnecessarily
stringMap = stringMap.replace(/{/g,'');
stringMap = stringMap.replace(/}/g,'');
stringMap = stringMap.replace(/ /g,'');
Split the mapString by , and for every pair split again by =, extracting keys and values as you go. These will need to be parsed to their correct data-types before adding to a javascript array jsArr:
var pairArray = mapString.split(",");
pairArray.forEach(function(pair) {
var values = pair.split("=");
var longString = values[0];
var intString = values[1];
var myLong = parseFloat(longString);
var myInt = parseInt(intString);
jsArr.myLong = myInt;
}
Where jsArr has been defined previously.

How to store and retrieve JSON data into local storage?

I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}

parse url to get id using javascript regex

I am writing a router which will parse the url and redirect to necessary components in the code, when I change my url and pass object id with it, I want to parse it using regular expression and route it to get that object by id.
mysite.com/blah#path=folder/?folderId=klafjlka
How do I parse this url using javscript regex and route it to that folder
With reference to backbone, I want to write a code which does this, but I'm not using backbone
routes : { "folder/:id" : "handler" },
I tend to find that using .split normally creates much more readable code in these situations.
If you use window.location.hash to get your data originally, you'll be left with
#path=folder/?folderId=klafjlka
Eliminating the first lot of un-needed stuff. The rest can be simply done with a split and a looped split.
//Remove the initial hash from the window.location.hash
var hash = window.location.hash.substr(1),
//Split it down so we have ["path=folder","folderId=klafjlka"]
paramSplit = hash.split("/?");
var params = {};
for (var x=0; x<paramSplit.length; x++){
//Split it at the equals
var split = paramSplit[x].split("=");
params[split[0]]=split[1];
}
console.log(params);
Params should return
{
path: "folder",
folderId: "klafjlka"
}
Which is easy to use for whatever your purposes are.
If your url is in a string and has always the same structure
var url = 'mysite.com/blah#path=folder/?folderId=klafjlka';
var re = /#path=(.+?)\?folderId=(.*)/i
var args = url.match(re);
var path = args[1];
var id = args[2];
this searches for #path= and captures the following characters until ? and then searches for ?folderId= and captures everything else.
Now path will contain folder/ and id wil contain klafjlka.

converting request.querystring using toString()

In JScript, why do I get the error "Object doesn't support this property or method" when I try to convert request.querystring to a string using toString()?
var params = Request.QueryString;
var params = params.toString();
Background info:
I'm trying to convert the querystring to a string so that I can perform a regex replace and remove certain items when they appear in the url.
var param = param.replace(/([?&])(allow)=[\w-]+/g, "");
I recently discovered the solution to this problem.
var params = Request.QueryString;
should be:
var params = Request.QueryString.Item;
There is no need to convert params to a string after that to manipulate the query string. Further you have access to everything in the query string by calling Request.QueryString("param").Item.
Example:
http://www.mysite.com?q=query&name=george
var name = Request.QueryString("name").Item;
I don't know -- weird Microsoft JScript implementation.
I had the same problem.
var strParams = new String(params);
seems to work though.

Categories