Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
Use with AIvar test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Answer from Joseph on Stack OverflowSince array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
Use with AIvar test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
You must replace all your
"'" to
"\"" Then you can use JSON.parse() for convert your string into an array. Just like this:
var answer = "['2012-2','2012-3','2012-4','2013-1','2013-2','2013-3','2013-4','2014-1']";
answer = answer.split("'").join("\"");
var arrPeriods = JSON.parse(answer);
var tr = $('<tr><td>Title</td></tr>');
$.each(arrPeriods, function(index, value) {
tr.append('<td>' + value + '</td>');
});
$('table').append(tr);
You must use jQuery method .append() instead to add td's after converting your string to an array.
NOTE: I suggest to return an array from backend if possible it will be more efficient. This solution is just a temporary fix for now
var arrPeriods = "['2012-2', '2012-3', '2012-4', '2013-1', '2013-2', '2013-3', '2013-4', '2014-1']";
var myArray = arrPeriods.replace(/\[|\]|'/g, '').split(',');
var tr = $('<tr><td>Title</td></tr>');
$.each(myArray, function(index, value) {
tr.append('<td>' + value + '</td>');
});
$('table').append(tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1></table>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Since new Date(2015,9,25) is not valid JSON, than you need to use eval(yourString) to parse your string to valid Object:
console.log(eval('[{ date: new Date(2015,9,25), NAV: 12},{ date: new Date(2016,9,25), NAV: 22}]'));
You can convert to a valid Javascript object using function
JSON.parse(str);
but string should be in valid json format.
I think that the best way of doing this, as Douglas Crockford (one of the biggests gurus of JavaScript) suggests in here is using the JSON native parser, as it is not only faster than the eval(), it's also more secure.
Native JSON parser is already available in:
- Firefox 3.5+
- IE 8+
- Opera 10.5+
- Safari Safari 4.0.3+
- Chrome (don't know which version)
And Crockford has made a safe fallback in javascript, called json2.js, which is an adaption of the eval() approach, with some security bits added and with the native JSON parsers API. You just need to include that file, remove its first line, and use the native JSON parser, and if it's not present json2 would do the work.
Here is an example:
var myJSONString = '{ "a": 1, "b": 2 }',
myObject = JSON.parse(myJSONString);
Once parsed you'll get an object with attributes a and b, and as you may know, you can treat an object as a hash table or associative array in JavaScript, so you would be able to access the values like this:
myObject['a'];
If you just want a simple array and not an associative one you could do something like:
var myArray = [];
for(var i in myObject) {
myArray.push(myObject[i]);
}
Lastly, although not necessary in plain JavaScript, the JSON spec requires double quoting the key of the members. So the navite parser won't work without it. If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" ); approach.
Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.
function malformedJSON2Array (tar) {
var arr = [];
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
arr[i] = {};
pair = cur.split(':');
arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return arr;
}
malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]
That code will turn your string into an Array of Objects (plural).
If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:
function malformedJSON2Object(tar) {
var obj = {};
tar = tar.replace(/^\{|\}$/g,'').split(',');
for(var i=0,cur,pair;cur=tar[i];i++){
pair = cur.split(':');
obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
}
return obj;
}
malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}
The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.
Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.
<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>
I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.
I have something like this: [['1', 'client1'], ['2', 'client2'], ['3', 'client3']] and would like to get: 1 - client1.....
The .value should be valid JSON or RegExp or String methods need to be used to convert invalid JSON to valid JSON. Note the single quotes at HTML attribute surrounding the value and double quotes within the value of the attribute
[["1", "client1"], ["2", "client2"], ["3", "client3"]]
You can then use JSON.parse() to convert JSON string to JavaScript object and use for..of loop to iterate each element of each nested array.
let value = JSON.parse(clients.value);
for (let [a, b] of value) {
console.log(a, b)
}
<input id="clients" value='[["1", "client1"], ["2", "client2"], ["3", "client3"]]'>
document.getElementById("clients").value
is a string, not an array. If you do :
for(var i =0; i < clients.length; i++)
you are actually iterating over every letter of the string, not every word.
What you can do is type client1,client2,client3 in your input field, then split them this way :
const clients = document.getElementById("clients").value.split(",") // ["client1","client2","client3"]
["123","234","345"] is an array of string, where as 123 is an integer.
You can convert this to string using toString before searching it in array
console.log($.inArray((value['id'].toString(), selectedProjectTasks));
I believe the answer lies in the $.inArray() docs, where it says
The comparison between values is strict. The following will return -1 (not found) because a number is being searched in an array of strings
You should either convert your new array to numbers or your compared value to a string. Then it should work.
var arr = "abcdef".split(''); // creates an array from a string
var str = arr.join(''); // creates a string from that above array
From String to Array you can Use split() Method
var str = "How are you doing today?";
var res = str.split(" ");
console.log(res); // How,are,you,doing,today? it will print
From Array to String you can use Join() method or toString() Method
To parse it you need to use double quotes instead of single.
This should work:
services = '["service1", "service2", "service3"]'
JSON.parse(services)
This is used to convert string which is array into pure array
var a = '[Aakash,akash]'
a.replace(/\[|\]/g,'').split(',')
(2) ["Aakash", "akash"]