Deserialize JSON string into array of list - javascript

I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"

I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)

The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15

You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]

This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]

var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

Related

How to make javascript turn a multidimensional array into a string?

I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much.
My array could look like the following:
[[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]
When I print the array I see:
0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2
The output that I am expecting is what the original array looks like.
I have also tried the following code:
alert("[[" + myArray.join("],[") + "]]");
This works for almost everything, I get an output of:
[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...
And I would like to see what the origional array looks like with the brackets. I would also like to stay away from JSON.stringify(); and JSON.parse();
JSON.stringify() and JSON.parse() will do exactly what you ask for. Try it out:
var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]];
var str = JSON.stringify(arr);
alert(str);
var parsed = JSON.parse(str);
alert(parsed);
console.log(parsed);

Template Literals for Javascript Arrays

When i try to put an array into a JavaScript array, a la,
> `${[1,2,3]}`
I get back this
'1,2,3'
and not
'[1,2,3]'
in the latest Node & Chrome.
I am missing something incredibly obvious, but need it spelled out to me nevertheless : )
You should use JSON.stringify(array)
It can help you to predict conversion to the string any arrays in this array.
const array = [["expected","test",1],0];
const arrayStr = JSON.stringify(array);
const templateResAsString = `${array}`; // expected,test,1,0
const templateResAsarray = `${arrayStr}`; // [["expected","test",1],0]
By the default, the values that are interpolated into a template literal are converted to their string representation.
For objects that means calling their .toString() method. The string representation of an array is simply a comma separated list of the strings representation of its elements, without leading [ or trailing ]:
console.log(
[1,2,3].toString()
);
Consolodiated list including above answers:
const arr = [1,2,3,4,5,'foo','bar','baz']
console.log(JSON.stringify(arr));
console.log(JSON.stringify(arr, null, 2));
console.log(arr.toString());
console.log(`${arr}`);
console.log(arr.join('\n'));
Good Luck...

Javascript Object not working with Native javascript methods like match(), replace etc

Here is the issue:
I go this Code:
var str = {"Acc":10 , "adm_data":"Denied"};
When I do something like:
console.log(str.Acc.match(/[0-9]+/g)) // To Get the Integer Value from the "Acc" key
Firebug Screams:
TypeError: str.Acc.match is not a function
console.log(str.Acc.match(/[0-9]+/g));
See Image:
I always do something like:
var str = "Hello _10";
console.log(str.match(/[0-9]+/g)) // This Works
Why is the Object thingi not working?
PLEASE NOTE:
As mentioned by #Fabrício Matté. The issue was that I was trying to
pass an integer Value to the .match method which does not belong
to integers. The solution was to do what #kundan Karn Suggested. Something like:
str.Acc.toString().match(/[0-9]+/g)// Converting it first to string then match. It worked!
match function works with string. So convert it to string first
str.Acc.toString().match(/[0-9]+/g)
It works just fine: http://jsfiddle.net/nKHLy/
but in order to get rid of the error you might want to try:
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(String(str.Acc).match(/[0-9]+/g));
or
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(str.Acc.toString().match(/[0-9]+/g));
To know the difference between the 2 options, check: What's the difference between String(value) vs value.toString()

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 separate a comma delimited variable into multiple variables?

This is probably very elementary, but I'm still learning.
I've imported a record from an XML file and have the result :
"a,b,c,d,e,f,g,h"
I would like to end up with 8 separate variables, one for each comma delimited value.
What is the shortest way to code this using javascript?
if you .split() the list, you'll end up with a single array with 'n' number of elements. Not -exactly- 8 separate variables, but 8 elements that can be accessed individually.
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split( ',' );
alert( myArray[ 4 ] );
use split()
js>s = "a,b,c,d,e,f,g,h"
a,b,c,d,e,f,g,h
js>a = s.split(',')
a,b,c,d,e,f,g,h
js>a[0]
a
js>a[4]
e
Use split().
In your case, xml_string.split(',');
If you have the result as a string, use the split method on it:
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split(",");

Categories