How to convert a string to an array in javascript? - javascript

I have an input on a form which stores values as an object.
jQuery('#inputId').val()
returns something like
'[{"Id":"123","Name":"A","PathOfTerm":"A","Children":[],"Level":0,"RawTerm":null},{"Id":"234","Name":"B","PathOfTerm":"B","Children":[],"Level":0,"RawTerm":null}]'
as one single string. Is there any way to either prevent this from automatically converting to a string (maybe not using .val?) or to convert this from a string to something I could work with?

Here you go
var array = JSON.parse(jQuery('#inputId').val());

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

Convert String of certain format to JSON in javascript

I have a string of the format
var str = "{key1=value1, Key2=value2}"
I need to convert this into a json object to be able to iterate through it.
Any suggestions on how this can be done? there can be any number of keys
You need first to "JSONize" this string you are getting so it can be converted to a JavaScript object using the JSON class. My guess, if the string has always this format ({key=value, ...}), is that you could parse it first like this:
var parsedString = yourString.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"')
This way, from this: "{key1=value1, Key2=value2}" you get this: '{"key1":"value1", "Key2":"value2"}'.
Then, as someone suggested, just use JSON.parse(parsedString) to get your JS object.

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

how to insert text into json using jquery/javascript [duplicate]

This question already has answers here:
Serializing to JSON in jQuery [duplicate]
(11 answers)
Closed 9 years ago.
How to insert text into json array using jquery/javascript .
supposing I have data as
some numbercodes in a text file format 123, 456, 789
I want to get them in a json array format using javascript/jquery.
var nuumbercodes = [ "123","456","789" ];
If you have a well formatted text string with comma separated numbers, like this '123,456,789'
This should have no spaces or tabs,
Then you can convert it simply into a JavaScript array.
var myTextwithNuumbercodes='123,456,789';
var numbercodes=myTextwithNuumbercodes.split(',');
returns ['123','456','789']
if you have a JSON string like this '[123,456,789]' then you get a javascript array by calling JSON.parse(theJSONString)
var numbercodes=JSON.parse('[123,456,789]');
returns [123,456,789]
notice the "[]" in the string ... that is how you pass a JSON array
toconvert it back to a string you can use JSON.stringify(numbercodes);
if you have a total messed up text then it's hard to convert it into a javascript array
but you can try with something like that
var numbercodes='123, 456, 789'.replace(/\s+/g,'').split(',');
this firstly removes the spaces between the numbers and commas and then splits it into a javascript array
in the first and last case you get a array of strings
u can transform this strings into numbers by simply adding a + infront of them if you call them like
mynumbercode0=(+numbercodes[0]);// () not needed here ...
in the 2nd case you get numbers
if you want to convert an array to a string you can also use join();
[123,456,789].join(', ');
Assuming your data is in a string, then split it on commas, use parseInt in a for loop to convert the string numbers into actual Numbers and remove the whitespace, then JSON.stringify to convert to JSON.
You could use .push() push values at the end of an array. After that you could use JSON.stringify(nuumbercodes) to make a JSON string representation of your Array.

How can I check if variable contains Chinese/Japanese characters?

How do I check if a variable contains Chinese or Japanese characters? I know that this line works:
if (document.body.innerText.match(/[\u3400-\u9FBF]/))
I need to do the same thing not for the document but for a single variable.
.match is a string method. You can apply it to anything that contains string. And, of course, to arbitrary variable.
In case you have something that is not string, most objects define .toString() method that converts its content to some reasonable stringified form. When you retrieve selection from page, you get selection object. Convert it to string and then use match on it: sel.toString().match(...).
afaik you can to the same with a variable... document.body.innerText just returns the text of the body. Therefore you can just do
myvar.match(...)
Here's an example: http://snipplr.com/view/15357/

Categories

Resources