JSON parsing and printing JSON object with variable name - javascript

I'm having trouble printing an object with a variable name. It works when I hard code it.
var objectVarName = "lat";
var obj = jQuery.parseJSON(JSON.stringify(msg));
// {"lat":"93"} is what JSON.stringify(msg) prints
$('#display').prepend("<br/><br/>" + JSON.stringify(msg));
//obj['lat'] works, obj[objectVarName] does not
$('#display').prepend("<br/><br/>" + obj['lat']);

Double check that your variable name, casing, etc are correct...your code works if msg is a valid object, here's what I tested:
var msg = {"lat":"93"};
You can test/see the result here, I changed .prepend() to .append() so the output is in order, no other changes besides that, the result is:
{"lat":"93"}
93

Related

sessionStorage.setItem with JSON.stringify causes javascript function to fail

I am storing two items in sessionStorage, an integer and a string array. I can see the items in Chrome Dev Console (Application - sessionStorage) and they are correct.
The values as it shows now in the Chrome Dev Console are:
HTTP_Index 4
HTTP_History ["Start","text_14","text_7","text_10"]
In a javascript function, I retrieve them from sessionStorage:
var HTTP_Index = sessionStorage.getItem(HTTP_Index);
var HTTP_History = sessionStorage.getItem(HTTP_History);
p_Index = JSON.parse(HTTP_Index);
p_History = JSON.parse(HTTP_History);
I decrement the index:
p_Index = p_Index - 1;
console.log("HTTP_Index Now " + p_Index);
and the log shows that the value is now 3.
Next I store the value p_Index back to sessionStorage:
sessionStorage.setItem("HTTP_Index", JSON.stringify({ "p_Index" });
Whether I enclose p_Index in quotes or not, the dev console now shows the function as "undefined."
Next I tried to do it like this:
sessionStorage.setItem("HTTP_Index", JSON.stringify({ "p_Index" });
but same problem. So finally I tried this:
var obj = { HTTP_Index: p_Index };
var objJSON = JSON.stringify(obj);
sessionStorage.setItem(objJSON);
But the Chrome dev console shows:
Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present.
What am I doing wrong in using JSON.stringify for sessionStorage.setItem?
Thanks for any help.
When using .setItem you must set a key, and then the value you want to store.
In the case of your first example, you're doing this but have made a simple typo. Also you want to stringify the contents in p_Index, not the string "p_index", so, you need to remove your quotes around it when stringifying:
sessionStorage.setItem("HTTP_Index", JSON.stringify(p_Index)); // <-- missing this closing bracket
And so you'll get a syntax error here.
In the case of your second example (attempt), you're not using valid syntax as you're setting an object with no value.
In your third example, you're trying to set the value to be the stringified object (so your value is just the string, not the object), and so you're not specifying a key. To do this you can use:
var objJSON = JSON.stringify(p_index);
sessionStorage.setItem("HTTP_Index", objJSON);
In your latest example:
var obj = { HTTP_Index: p_Index };
var objJSON = JSON.stringify(obj);
sessionStorage.setItem(objJSON);
sessionStorage.setItem first argument must be the key which you want to set and the 2nd is the data which you are going to store.
So you miss the key/name.

Change the value of javascript variable dynamically

I have javascript variable var result as following which has java variable that have JSON data like this
var result = <%=JsonData1%> ;
alert(result.toSource());
Above code similar to this code as showing on alert message
var result= [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
but I need to place a single quote on JSON data
'[{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}]'
and place it in new javascript variable like this
var json_pre = result;
alert(json_pre);
but when I change my result data that placed in new json_pre variable as in this link How to add single quote in the variable in Javascript?
var json_pre = "'" +result+ "'";
alert(json_pre.toSource());
then json data shows me like this on the alert message
'[{year:(new Date(-2208058200000)), value:6694}, {year:(new Date(-2207971800000)), value:50}, {year:(new Date(-2208403800000)), value:4776}, {year:(new Date(-2208317400000)), value:29006}, {year:(new Date(-2208231000000)), value:1751}]'
As I have tried every method that given me on that link.So anyone can help me in this?
result is not JSON, but a JavaScript object.
What you need to do is to stringify your object to JSON and then add the quotes:
var result = [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
var result_pre = "'" + JSON.stringify(result) + "'";
console.log(result_pre);
But it is questionable why you would even need that.
You need to understand the single quotes does not make an object a string. When you are trying to store it in a variable I guess you are making the same mistake again.
when you do this
a={"key":"value"}
b="'" + a + "'";
You get a string representation for consoles, if you want a JSON string to be stored in a variable you need to do this
var json = JSON.stringify(result);
alert(json);
You don't need quotes for that.

HTML JavaScript localStorage

if(localStorage.getItem('arr')){
document.getElementById("scores").innerHTML = localStorage.getItem('arr');
}
var stored_arr = JSON.parse(localStorage["arr"]);
document.getElementById("scores").innerHTML += stored_arr;
var newarr = stored_arr.split(",");
document.getElementById("scores").innerHTML += newarr[0];
Here's a snippet of code. It checks for localStorage and it it exists prints it out(for testing). Then it parses it and stores it in the stored_arr variable, and also displays it. At this point it would have
["xxxxxxx","yyyyyyy"]xxxxx,yyyyy
displayed, where xxxxx,yyyy is contained in the stored_arr variable. I need a way to split that up by the comma and tried the final two lines of code and nothing happens.
Am I wrong to use JSON.parse() or is it the way I'm trying to split it?

Json to string to javascript array

i have a json string returned to a hidden value and i want to assign it to a javascript array and print each element of the array.
Json string returned by hdn_client_windows - ["5703","5704"]
Javascript array assignment is as below.
var times = $('#hdn_client_windows').val();
alert(times[0]); // this printed only--> [
alert(times[1]); // this printed only--> "
what am i doing wrong ?
You need to parse the JSON into an array with JSON.parse first:
var times = JSON.parse($('#hdn_client_windows').val());
Since you are already using jQuery, it might be a good idea to defer to $.parseJSON instead just to be on the safe side (full compatibility with old browsers):
var times = $.parseJSON($('#hdn_client_windows').val());
Use $.parseJSON().
var str = '["5703","5704"]';
var times = $.parseJSON( str );
You have to parse the string first using JSON.parse (older browsers might require you to load this in):
var times = JSON.parse($('#hdn_client_windows').val());
alert(times[0]); // Will display first item
alert(times[1]); // Will display second item
You could use jquery's parseJSON() function.
var str = '["5703","5704"]';
var parsed = $.parseJSON( str );
The parsed object now contains the array: ["5703","5704"]
Reference - jQuery.parseJSON( json )
"Takes a well-formed JSON string and returns the resulting JavaScript object."

How do I store xml as a string variable in javascript?

I trying to store a piece of xml into a string variable in javascript and in IE8 it keeps throwing an error. FireFox doesn't show the error but of course in IE8 it does. Swictching browsers isn't an option so I have to try to solve this one.
The purpose of the function is to check if the items of a list exist in an xml object or not. So if there is a better way to do that check I am open to that as well. The system we pull from has a function to convert the xml to a string. At the bottom is an output of what that retrieves. Here is the function.
function commodityExists(newCommodityCode){
var comExists = new Boolean(0);
newCommodityCode = ">" + newCommodityCode + "<"
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
strXML = strXML.toString();
if(strXML.indexOf(newCommodityCode,0)>0){
comExists=true;
}
return comExists;
};
Here is the output from strXML.toString(); but as you can see it is essentially xml.
var strXML = ‘<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>’;
I don't know what you think the code is doing, here is an explanation of what it does:
> function commodityExists(newCommodityCode){
> var comExists = new Boolean(0);
Do you really want a Boolean object? This function might return a Boolean object or primitive depending on what happens later. Consider:
var comExists = false;
.
> newCommodityCode = ">" + newCommodityCode + "<"
That overwrites whatever value was passed to newCommodityCode from the call.
> var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
I can't see how that throws an error, it's a simple assignment of a string.
> strXML = strXML.toString();
That effectivly does nothing - it calls the toString method of a string, which will just return the same string.
> if(strXML.indexOf(newCommodityCode,0)>0){
That test will always be false, since the value of nweCommodityCode is hard coded in the function and does not exist in the (hard coded) value of strXML.
> comExists = true;
> }
> return comExists; };
The function will always return false (though the original will return a Boolean object with a value of false).
You're creating a string:
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
^--- ^---
then converting that string to... a string?
strXML = strXML.toString();
Where would this tw object be defined that you seem to be attempting to use? Because as your code is written now, you're not calling a .toXMLString() method on something in this tw object. You're just assigning the literal text of an object call as a string itself.
The approach I was trying to take will not work because I am dynamically populating the xml so there is no way for me to escape the characters (well there probably is somehow but clearly it is not worth it). Storing HTML or XML code in javascript variables
Instead I am moving the comparison to the server side instead of retrieving the xml and comparing on the client side and posting back the results via ajax unless someone has a better reccomendation.

Categories