Parsing a localstorage object gives uncaught syntax error? - javascript

I'm trying to save numbers given by Math.random. I save them in array which gets saved into localStorage. I then want to append each new array of numbers when Math.random is used. It's easier if you view the code I tried wrting.
var nums = [];
for (var i = 0; i < 5; i++) {
var num = Math.floor(Math.random() * 50);
nums.push(" " + num);
}
console.log(nums);
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "";
localStorage.setItem(name, old + JSON.stringify(data));
}
if (localStorage.num) {
appendToStorage('num', nums);
} else {
localStorage.setItem("num", JSON.stringify(nums));
}
var nums2 = localStorage.getItem("num");
console.log(nums2);
document.getElementById("test").innerHTML = JSON.parse(nums2);
This doesn't work, though. Console says Uncaught SyntaxError: Unexpected token [
This error will work if you remove the JSON.parse on getElementById. I want it to be parsed, though, so the numbers are more easily viewed. How can I do this?

If you simply append a valid JSON string to another valid JSON string you don't get a valid JSON string. For example:
var myJSON = '{"thing": "data"}'; // valid
myJSON = myJSON + myJSON; // myJSON is now '{"thing": "data"}{"thing": "data"}', not valid
To do this reliably you'll need to parse your retrieved JSON, update the result, then stringify it again before storing it in localStorage.
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "[]";
var newData = JSON.parse(old);
newData.push(data);
localStorage.setItem(name, JSON.stringify(newData));
}
Note that this will return an array when you parse it, and that will cause you a problem when you try to set innerHTML. You'll need to unpack the array to some sort of text format first (thanks to jibsales for that).

Element.innerHTML takes a string as valid input, not an Array. May I suggest using JSON.parse(nums).join("");
Using this method would also allow you to not add the leading white space in your for loop and instead add the white space as the first parameter to the Array.join method. If you want each number on a new line, pass "\n".

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

JavaScript get url segment and parameter

I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)

JSON rows Extracting issue in JavaScript

I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!

How to convert a json formatted string into a json array in javascript

I am using the $.post() method to retrieve a json formatted string which looks like this:
{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}
In the success callback function of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.
// data returns {elementid:10},{elementid:11},{elementid:12},{elementid:14}, etc.
$.post('form.php',
{'postvalues' : input_ids},
function(data){
var elements = Array();
elements = [data];
for(var i=0; i<elements.length; i++) {
var value = elements[i]['elementid'];
alert('value = '+value);
}
});
When I do this, instead of getting value = 10, value = 11, value = 12, etc. in the alert box,
I get value = undefined
What must I change in the format of the variable 'data' so that it will be interpreted as array values and not a string?
thanks for your help
Your string isn't valid JSON if you don't have the '[' and ']' characters.
You can add those in , then parse it using the jQuery.parseJSON()[docs] method.
elements = jQuery.parseJSON( '[' + data + ']' );
...but it would be better if you sent correct JSON data from the server.
Also, your JSON keys must be wrapped in double quotes.
{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}
Your query isn't returning valid JSON. It should be [{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}] and not {elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}. Is there any way you can fix that? Otherwise, you will have to do this:
elements = jQuery.parseJSON("[" + data + "]");
The right thing to do, however, is to return valid JSON from the server (if you have any control over that).
use JSON.parse(data) to put a string which contains a JSON object in a variable
Try this, it looks like you are getting passed an array (apart from the missing surrounding []), and if you tell jquery that it's json it'll parse it for you properly:
$.post('form.php', {'postvalues' : input_ids}, function(data){
for(var i=0; i<data.length; i++) {
var value = data[i]['elementid'];
alert('value = '+value);
}
}, 'json'); // telling it that the content received is json
Use the "for in" statement. Such as:
for (var x in data) {
console.log(data[x]['elementid']);
}
I tested it and it perfectly worked!
Hope this helps.
Ps. Console.log() output the result in the browser console (so it won't work in IE, of course).

Categories