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};
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);
}
So I have a function that makes an ajax call and returns a json string. I am having trouble trying to access the values that I need, below is my code of what I have and a few examples of what I have tried.
s.search().then(function (specials) {
var returnJSON = JSON.parse(specials[0]);
var x = returnJSON.location.x;
var y = returnJSON.location.y;
});
When I check the dev tools I'm getting the following error.
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Here is the the JSON returned value after I stringify it.
[{"feature":{"geometry":{"type":"point","x":-82.9172080701955,"y":42.55426092899978,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Postal","Match_addr":"48035, Clinton Township, Michigan","StAddr":"","City":"Clinton Township","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.922209,"ymin":42.549261,"xmax":-82.912209,"ymax":42.559261,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"48035, Clinton Township, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.03589825899667,"y":44.826904141314174,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.085899,"ymin":44.776904,"xmax":-83.985899,"ymax":44.876904,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.93987906956261,"y":42.065412162742234,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-83.98988,"ymin":42.015412,"xmax":-83.88988,"ymax":42.115412,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-82.93354923650725,"y":42.60054198222781,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.98355,"ymin":42.550542,"xmax":-82.88355,"ymax":42.650542,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.97095926895429,"y":42.07240087260328,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.02096,"ymin":42.022401,"xmax":-83.92096,"ymax":42.122401,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.6015125489642,"y":42.943655651388326,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"SubAdmin","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.839514,"ymin":42.705656,"xmax":-84.363514,"ymax":43.181656,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"}]
I am trying to access candidates location x value and y value.
There are some Strings in your JSON on separate lines. When you copy and paste your JSON in a linter (e.g.: json linter), you will see the errors.
EDIT:
You edited your question so you are now using valid JSON.
There is no need to parse your JSON when you already have valid JSON. You can just select the correct keys. Looking at your JSON, you can select your x and y like this:
var returnJSON = specials[0];
var x = returnJSON.feature.geometry.x;
var y = returnJSON.feature.geometry.y;
Checkout this codepen for an example.
You don't need to "parse" JSON returned from a service usually. It is already a Javascript object in the then callback.
s.search().then(function (specials) {
var firstItem = specials[0];
var x = firstItem.location.x;
var y = firstItem.location.y;
});
It should be noted, however, that the first item that comes back in your array of specials does not have a property location accoring to the JSON example you posted.
Perhaps you were after firstItem.feature.geometry.x, but im not sure.
I’ve created a string…
{"atts": [{"name": "wedw"}, {"type": "---"}]}
I pile a bunch of these together in an array based on user input and attach them to another string to complete a JSON object that tests out as valid.
So I end up with a global array called fields with a bunch of these little snippets.
So how do I change the name "weds" with a new name? I’ve tried...
function changefieldname(pos){
var obj = JSON.parse(jsonstring);
var oldname = obj.tracelog.fields[pos].atts[0]["name"];
var newname = document.getElementById("newlogfieldname"+pos).value;
fields[pos].replace(oldname, newname);
//writejson();
}
And a bunch of variations. I know everything is checking out correct interms of the variables pos, oldname, and newname. I also know that fields[pos] returns the string in the array I want to correct but it’s not happy. I also tried converting fields[pos] to a string, but the replace function doesn't work on it. I’m sure there is a good reason.
Why even bother trying to do some kind of replacement? Just assign it a new value:
obj.tracelog.fields[pos].atts[0]["name"] = newname;
I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers