HTML5 localstorage adding in double quotes - json

I'm currently assigning the value of a field to a variable:
userName = document.getElementById('userName').value;
Then assigning that variable to localstorage:
localStorage.setItem('userName', JSON.stringify(userName));
Retrieving that item here:
var retrievedUserName = localStorage.getItem('userName');
Then trying to output the contents of the item into a HTML div:
document.getElementById("response-heading-name2").innerHTML = retrievedUserName;
...but when I check the HTML, it's outputting the string with double quotes around it: "My name"
Does anyone know why this is happening, and how I can stop the double quotes from appearing?

This has nothing to do with local storage.
The quotes are added when you convert the data structure to JSON with JSON.stringify.
You should convert the JSON back to a JavaScript data structure with JSON.parse after you retrieve it from local storage.
The point of using JSON is to ensure that what you store is a string because local storage can only store strings.
Since you are getting the value of an input, you know that it will be a string. So you could dispense with JSON altogether and not JSON.stringify it in the first place.

localStorage always store the string data with double quotes, when you are retrieving the same data you will get with double quotes. So just use JSON.parse to fix it.
var retrievedUserName = JSON.parse(localStorage.getItem('userName'));

Related

Converting a string of an array into an array in JS

I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?
You can use JSON.parse() to convert a string into an array.
const response = "[1,2,3]";
console.log(JSON.parse(response));
You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object
Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.
let str = '1,2,3,4';
let arr = str.split(',');
Just pass in whatever delimiter you used to join the elements.
OR
If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer

How to parse Cosmosdb insert return value of (insertedIds)

When I insert an object into CosmosDB (MongoDB API), the result contains a property insertedIds.
When I console.log(insertedIds) I get
[ 5a6c46c85ac3cc4bb01ebcbb,
5a6c46c85ac3cc4bb01ebcbc,
5a6c46c85ac3cc4bb01ebcbd ]
and the typeof() is an object, for each element, although I'm not sure why - they just seem to be strings.
When I go through and JSON.stringify each element, I get (with surrounding double quotes) "5a6c46c85ac3cc4bb01ebcbb","5a6c46c85ac3cc4bb01ebcbc","5a6c46c85ac3cc4bb01ebcbd"
What is the right way to parse a CosmosDB Insert Result, and get the insertedIds as an array of strings?
Do I really have to go through and "stringify" then "de-string by removing quotes" for each returned Id? That is a huge overhead with large arrays.
Note: I believe this has something to do with MongoDB's bson/strict json: https://docs.mongodb.com/manual/reference/mongodb-extended-json/ but still not sure how to parse it.
you could use the following example:
JSON.parse(this_is_double_quoted);
JSON.parse("House");
.parse would return the value without quotes. more information can be found in the following post: remove double quotes from Json return data using Jquery

Json : getting the unwanted result

I'm using json plugin to get the response in json.
But I m getting the unwanted result:
Here is what I get:
{"data":"[[\"service\",\"webservices\",\"document\"],[\"validation\",\"adapters\",\"server\"]]","records":25,"recordsTotal":75}
originally the data var in my action class is like this:
[["service","webservices","document"],["validation","adapters","server"]]
but json plugin adds the backslash.
The wanted result is that:
{"data":[["service","webservices","document"],["validation","adapters","server"]],"records":25,"recordsTotal":75}
Is there a way to get the later result ?
Thanks
You're representing the data as a PHP string. " is obviously a reserved character in JSON, so your serialization library is dutifully escaping the quote using /.
If you set up the PHP variable so it's an array of arrays, instead of a string representing an array of arrays, then your JSON serialization will work fine.

escape special characters inside json from a data attribute

I have json stored in data attributes.
<div data-dataarray="[["Shipper","Ship No","Weight"],["1WWWQUICK\PARTSCOM",1,1]]">
data = $('#'+moduleId).data('dataarray')
So data is now a string.
Which I then need to parse to get it back to json:
jsondata = JSON.parse(data);
This json can have special characters (notice the backslash)... which causes an error. How can I escape them before/while parsing?
firstly
I think the html5 data attributes need to have a form like data-xyzUserVariable. then you retrieve them using jquery.data("#xyz_id", "xyzUserVariable"),
secondly
However, be wary that jQuery cleverly attempts to convert the data to a suitable type (booleans, numbers, objects, arrays or null) and avoids touching the DOM.
thirdly
your json seems to be an array of objects ..is it missing an ending bracket ']' ?

SHA1 hashed password converted to object if is replaced in JSON object

I would like to ask on this:
I have object with data for request and i would like to hash value options.data.password:
Here is how i do it:
var hashedPassword = CryptoJS.SHA1(options.data.password);
alert(hashedPassword); // This is correctly value
options.data.password = hashedPassword;
Problem is that if i looked into updated JSON object i saw something like this:
But i was expected just hashed string value, not object.
NOTE: If I update value manually (without hashing function) is everything displayed correctly.
How can i solve it?
Thanks for any help.
Per the CryptoJS documentation:
The hash you get back isn't a string yet. It's a WordArray object. When you use a WordArray object in a string context, it's automatically converted to a hex string.
Your property assignment and subsequent JSON.stringify do not know you want to use it as a string.
You need explicitly make it a string by calling its .toString(). Again, from the docs:
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
options.data.password = hashedPassword.toString(CryptoJS.enc.Base64);
FYI, The receiving end of this hash needs to know what encoding method was used (Base64 in this example) in order to accurately work with it.
From the documentation of CryptoJS:
The hash you get back isn't a string yet. It's a WordArray object. When you use a WordArray object in a string context, it's automatically converted to a hex string.
The JavaScript object returned has a toString() method which is why when you use it as a string (in alert) it gets converted to one.