How to parse an array inside a string into a javascript arrray - javascript

I have a string received from a database call as follows:
"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"
I would like to parse the string into a typescript/JS array so that it is as follows:
[
{'url':'https://www.example.com/','category':'popular'},
{'url':'https://example2.com/','category':'new'}
]
How can I go about doing this? JSON.parse won't work as the string does not resemble a stringified JSON. Thanks!

Assuming there are no strings in it containing ', you can replace all occurrences of the single quote with double quotes, then you can parse it:
const str = "[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]";
const arr = JSON.parse(str.replace(/'/g,'"'));
console.log(arr);

Replace single quotes with double quotes then JSON.parse
JSON.parse(
"[{'url':'https://www.example.com/','category':'popular'},{'url':'https://example2.com/','category':'new'}]"
.replace(/\'/g, '"')
)

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/

string to json converter laravel return data json_encode

"[{"question":false,"choices":["Database","Email","Command line"],"correctAnswer":1},{"question":false,"choices":["Horizon","Sunset","Nightfall"],"correctAnswer":1}]"
convert to this
[{"question":false,"choices":["Database","Email","Command line"],"correctAnswer":1},{"question":false,"choices":["Horizon","Sunset","Nightfall"],"correctAnswer":1}]
Instead of (Invalid string)
"[{"question":false,"choices":["Database","Email","Command line"],"correctAnswer":1},{"question":false,"choices":["Horizon","Sunset","Nightfall"],"correctAnswer":1}]"
Use this
'[{"question":false,"choices":["Database","Email","Command line"],"correctAnswer":1},{"question":false,"choices":["Horizon","Sunset","Nightfall"],"correctAnswer":1}]'
For example :
var str = '[{"question":false,"choices":["Database","Email","Command line"],"correctAnswer":1},{"question":false,"choices":["Horizon","Sunset","Nightfall"],"correctAnswer":1}]'
console.log(JSON.parse(str))
Reason:
If there is double quote inside a string then you can not use a double quote to enclose that string. As there is always a double quote inside a JSON string, you can use a single quote('') or a template string (``) to enclose it.
You need to use JSON.parse() because It's already stringified.

Converting a string to array in javascript without eval()

I want to implement a counter for unique articles visited in my website, basically storing the ids of the articles the user has visited in a cookie. My issue is that the recovered value is, of course, a string. How would you convert a string that looks like this "['test','b','c']" to an array? Using eval is not advised, right?
Use JSON.parse to turn a string into an array:
const string = '["test","b","c"]';
const arr = JSON.parse(string);
console.log(arr[0]);
Note that you need to have proper JSON formatting, though - keys and non-numeric values need to have double quotes. Easiest to serialize automatically with JSON.stringify:
const arr = ["test","b","c"];
const str = JSON.stringify(arr);
console.log(str);
If you absolutely cannot change the single-quotes in the string you're working with originally, then use replace to turn it into something parseable:
const str = "['test','b','c']";
const jsonFormattedStr = str.replace(/'/g, '"');
const arr = JSON.parse(jsonFormattedStr);
console.log(arr[1]);
While using JSON.parse() is the correct way to convert data strings to usable objects, the string in your question is not valid JSON syntax. Namely the single quotes will result in an unexpected token error.
If your only issue is the quotes, then it becomes trivial to prepare your data for parsing:
var str = "['test','b','c']"
// convert to double quotes
str = str.split('\'').join('"')
// now parse
var arr = JSON.parse(str)
console.log(arr)
You need to convert the quotes to double quotes, and then use JSON.parse
let string = "['test','b','c']";
// replace quotes with double quotes
let stringFixed = string.replace(/'/g, '"');
// parse the string
let result = JSON.parse( stringFixed );

JavaScript json.parse string error

I want to parse this string to an array
var string= "['one','two']";
var result= JSON.parse(string);
It throws an error
`Unexpected token ' in JSON at position 1'
I believe my approach is right I just can't figure out why its throwing that error.
You should use double quotes:
var string = '["one", "two"]';
You can't use single quote in a JSON string.
Just make it like this
var string= '["one","two"]';
var result= JSON.parse(string);
Json standard requires that the string have double quotes inside.

remove quotes before an array list using jquery

I have been strugling with a problem, I am using
var srlisthidden = $('#hiddenroutList').val();
srlisthidden returns an array of list but in quotes "['0015','0016']"
$.each(srlisthidden, function(i, value) {
});
But because of the double quotes on the beginning of the array,it is not allowing the list to iterate even, I tried many different options to remove the double quotes like regEx and
jQuery.parseJSON('['+srlisthidden+']'), but none of them worked, Please give me solution.
Try this out:
var x = "['0015','0016']"; // The value that you are grabbing
var sol = eval(x); // This returns the value as an array of strings.
Is this what you are trying to achieve?
You can achieve it like this as well
var to_parse = "['0015','0016']";
var array = parse.replace(/\[|]|'/g, '').split(',');
JSON requires inner quotes around strings be double-quotes escaped with a backslash; the parser doesn't play nicely with single quotes.
Clean up your string with regex:
var str = srlisthidden.replace(/\'/g, "\"")
Output: ["0015","0016"] (as a string)
Then parse as JSON:
JSON.parse(str)
Output: ["0015", "0016"] (as an array)

Categories

Resources