Convert string to Json in Javascript - javascript

My string is like this :
"['01',746],['02',0],['03',9994],['04',0],['05',0],['06',0],['07',0],['08',0],['09',0],['10',0],['11',0],['12',0],['13',0],['14',0],['15',0],['16',0],['17',0],['18',0],['19',0],['20',0],['21',0],['22',0],['23',0],['24',0],['25',0],['26',0],['27',0],['28',0],['29',0],['30',0],['31',0]"
I have tried $.parseJSON() or JSON.Parse() but does not work . I am gonna use this data for google chart . so i need it in the json format .
how can i do that ?

You need to convert the single quotes to double to be valid and you would need to wrap it in [] so it is a valid array format.
var str = "['01',746],['02',0],['03',9994],['04',0],['05',0],['06',0],['07',0],['08',0],['09',0],['10',0],['11',0],['12',0],['13',0],['14',0],['15',0],['16',0],['17',0],['18',0],['19',0],['20',0],['21',0],['22',0],['23',0],['24',0],['25',0],['26',0],['27',0],['28',0],['29',0],['30',0],['31',0]";
var myArray = JSON.parse("[" + str.replace(/'/g,'"') + "]");
console.log(myArray[0][0], myArray[0][1]); // "01" 746
But a better solution is to fix what is producing that string so it is a valid JSON object to start.

Related

Javascript - Parse a stringified arrays of strings

I have a string like so :
a= "['url1','url2','url3']"
coming from the server I want to convert it to array like :
arr = ["url1","url2","url3"]
but JSON.parse does not seems to be working and gives following error:
SyntaxError: Unexpected token ' in JSON at position 1
Thanks in advance.
You need to replace the single quotes with double quotes. An easy way to achieve this can be by replacing them with escaped quotes like this:
let validJSON = a.replace(/'/g, "\"")
JSON.parse(validJSON)
Your string needs to be in single quotes for JSON.parse to work in this example, also string representation in json uses double quotes as per standard.
JSON.parse('["url1","url2","url3"]')
Try to use this code:
a = "['url1','url2','url3']"
urls = a.split(',')
arr = urls.map(url => url.replace(/'|\[|\]/g, ''))
console.log(arr) // ["url1", "url2", "url3"]
https://jsfiddle.net/z1frh8ys/

Convert a string made from array toString() back to Array

I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?
The string which I have produced and need to convert back to an array is:
{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}
I tried to use the JSON Parser JSON.parse(text)
Format your string:
const text = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}'
console.log(JSON.parse(`[ ${text}]`))
You just need to format your string as an array in JSON format. You can do that like so:
JSON.parse('[' + text + ']')
The Below code should work:
var text_string = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}';
console.log(JSON.parse(`[${text_string}]`));

JS Change string format

I have a string in the following format :
One,Two,Three,Four
and I want to change its format to "One","Two","Three","Four"
I tried the following :
var items = ['One,Two,Three,Four'];
var quotedAndCommaSeparated = '"' + items + '"';
document.write(quotedAndCommaSeparated);
which adds the double quotes at the beginning and at the end of the string. I don't want to use replace because there might be values that have a comma.
Is there a way to split the initial string and return the wanted one?
Try this
items[0].replace(/^|$/g, '"').replace(/,/g,'","')
This should give you what you want. Split on the commas and then rejoin using the delimiter you are looking for.
var quotedAndCommaSeparated = '"'+items[0].split(',').join('","')+'"'

Convert array formatted strings to object

I got
[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]
this from google translator
However I tried
JSON.parse(xhr.responseText);
It return an error Unexpected token
The problem is that this string contains multiple commas making your json invalid.
You could try to replace it for a single one before parsing
var x = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]'
.replace(/,{2,}/g, ",") // 2 or more replace for 1
JSON.parse(x);
Or if you have access to whatever is sending this string fix the output.
First you should remove an extra [] brackets by replacing that.
ex,
[["汽車","car","Qìchē",""]]
should be:
["汽車","car","Qìchē",""]
EDIT: you can refer to this answer: Parse Google Translate Json C#
You should try:
var str = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]';
var objstr = $.parseJSON(str);

Converting String to Array and back in Javascript

I simply have a huge array in a string like this:
"test", "blabla", "anothertest", "et", "cetera"
I need to be able to convert it to an array, preferable without the " "'s still left over.
I have no idea how javascript would be able to do this, but I heard JSON was able to do something like this.
JSON is fine indeed:
var string = '"test", "blabla", "anothertest", "et", "cetera"';
JSON.parse('[' + string + ']');
Keep in mind that string must respect the JSON syntax. More precisely, you have to check that double quotes are used, the separator is a comma and so on.
If your string contains data in quotes, and separated with comma, it almost valid json. Just do this
var myparsedarray = JSON.parse("[" + yourstring + "]");

Categories

Resources