Converting associative array string to array - javascript

I've been trying to convert an associative array string but I can't seem to make it work.
I've tried the code below but it is not working.
var string = "{'custom_text_record': 'Text Here', 'fill_record': '0'}";
var s_obj = JSON.parse(string) ;
alert(s_obj['custom_text_record']);

You need to basically get JSON format from the associative array string,
The JSON format should be "{'custom_text_record': 'TextHere','fill_record':'0'}" before we use JSON parse function
Please try this.
var string = '{"custom_text_record": "Text Here", "fill_record": "0"}';
var jsonStrig = '{';
var items = string.split(',');
for (var i = 0; i < items.length; i++) {
var current = items[i].split(':');
jsonStrig += '"' + current[0].replace(/{|'|"|}|\s/g, '') + '":"' +
current[1].replace(/{|'|"|}|\s/g, '') + '",';
}
jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
jsonStrig += '}';
var s_obj = JSON.parse(jsonStrig);
console.log(s_obj['custom_text_record']);
Regex might be used to filter the single quote, double quote, and bracket, spaces which can appear in the associative array string.
I think we can convert any type of associative array string like '{ key : value }' style into the correct JSON format and finally get an array in this way.
I hope this would be helpful.

Related

;How encode string like \x31, etc?

i saw a code and that code had all string in a array.. And each array index was like: "\x31\x32\x33", etc..
How i can convert for example "hello" to that encode format?
if is possible, there a online encoder?
As the #nikjohn said, you can decoded the string by console.log.
And the following code I found from this question. And I made some changes, the output string will be in a \x48 \x65 form.
It will convert the string in a hex coding, and each character will be separated by a space:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("\\x"+hex).slice(-4) + " ";
}
return result;
};
var str = "Hello";
console.log(str.hexEncode());
The result of the above code is \x48 \x65 \x6c \x6c \x6f。
It is an hex coding encoding.
www.unphp.net
http://ddecode.com/hexdecoder/
http://string-functions.com/hex-string.aspx
are the few sites that can give you encoding and decoding using hex coding.
If you console log the string sequence, you get the decoded strings. So it's as simple as
console.log('\x31\x32\x33'); // 123
For encoding said string, you can extend the String prototype:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("\\x"+hex).slice(-4);
}
return result
}
Now,
var a = 'hello';
a.hexEncode(); //\x68\x65\x6c\x6c\x6f

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

split words,numbers from string and put it as 2D array in JavaScript

I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);

how to convert ["one","two","three","four "] to [one,two,thee,four] as array in jquery or javascript

I have a scenario. I will get all the data from service in the below shown array format.
but I need to convert that to by removing them as strings
var array1 = ["one","two","three","four"]
var array1 = [one,two,thee,four]
array contains strings to variables of the array.
Try,
var array1 = ["one","two","three","four"].map(function(val){ return window[val]; });
But the new array would contain the values of the variables not the variable itself.
There are no double quotes in that array. The quotes just delimit the string literals, when they are parsed into strings they don't have quotes in them.
If you wanted to remove all the quotes from a string which actually had some in it:
str = str.replace(/"/g, ""); // RegEx to match `"` characters, with `g` for globally (instead of once)
You could do that in a loop over an array:
for (var i = 0; i < array1.length; i++) {
array1[i] = array1[i].replace(/"/g, "");
}

Convert comma separated string to a JavaScript array

I have this string:
"'California',51.2154,-95.2135464,'data'"
I want to convert it into a JavaScript array like this:
var data = ['California',51.2154,-95.2135464,'data'];
How do I do this?
I don't have jQuery. And I don't want to use jQuery.
Try:
var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");
Use the split function which is available for strings and convert the numbers to actual numbers, not strings.
var ar = "'California',51.2154,-95.2135464,'data'".split(",");
for (var i = ar.length; i--;) {
var tmp = parseFloat(ar[i]);
ar[i] = (!isNaN(tmp)) ? tmp : ar[i].replace(/['"]/g, "");
}
console.log(ar)
Beware, this will fail if your string contains arrays/objects.
Since you format almost conforms to JSON syntax you could do the following :
var dataArray = JSON.parse ('[' + initialString.replace (/'/g, '"') + ']');
That is add '[' and ']' characters to be beginning and end and replace all "'' characters with '"'. than perform a JSON parse.

Categories