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, '"')
)
So, I have an object whose properties also contain json strings within them. When serializing this object, this is the string I get:
[{
"template": 1,
"action_json": "{\"id\":\"1\",\"action\":\"An action for all of IT!\",\"date_agreed\":\"2018-08-10\",\"complete_by\":\"2018-08-31\",\"responsible_departments\":[\"8\"],\"responsible_employees\":[\"1629\",\"112\",\"1374\"],\"priority\":\"High\"}",
"template_json": "{\"columns\":[{\"id\":\"id\",\"title\":\"Task Number\",\"default\":true,\"type\":\"auto\"},{\"id\":\"action\",\"title\":\"Action Agreed\",\"default\":true,\"type\":\"longtext\"},{\"id\":\"date_agreed\",\"title\":\"Date Agreed\",\"default\":true,\"type\":\"date\"},{\"id\":\"complete_by\",\"title\":\"Complete By\",\"default\":true,\"type\":\"date\"},{\"id\":\"responsible_departments\",\"title\":\"Responsible Departments\",\"default\":true,\"type\":\"option\"},{\"id\":\"responsible_employees\",\"title\":\"Responsible Employees\",\"default\":true,\"type\":\"option\"},{\"id\":\"priority\",\"title\":\"Priority\",\"default\":true,\"type\":\"option\",\"options\":[\"High\",\"Medium\",\"Low\"]}]}"
}, {
"template": 1,
"action_json": "{\"id\":\"1\",\"action\":\"Action numero uno\",\"date_agreed\":\"2018-08-10\",\"complete_by\":\"2018-08-10\",\"responsible_departments\":[\"8\"],\"responsible_employees\":[\"112\"],\"priority\":\"High\"}",
"template_json": "{\"columns\":[{\"id\":\"id\",\"title\":\"Task Number\",\"default\":true,\"type\":\"auto\"},{\"id\":\"action\",\"title\":\"Action Agreed\",\"default\":true,\"type\":\"longtext\"},{\"id\":\"date_agreed\",\"title\":\"Date Agreed\",\"default\":true,\"type\":\"date\"},{\"id\":\"complete_by\",\"title\":\"Complete By\",\"default\":true,\"type\":\"date\"},{\"id\":\"responsible_departments\",\"title\":\"Responsible Departments\",\"default\":true,\"type\":\"option\"},{\"id\":\"responsible_employees\",\"title\":\"Responsible Employees\",\"default\":true,\"type\":\"option\"},{\"id\":\"priority\",\"title\":\"Priority\",\"default\":true,\"type\":\"option\",\"options\":[\"High\",\"Medium\",\"Low\"]}]}"
}]
Which is fine, this is valid JSON.
The problem arises when I try to create a JavaScript object by parsing this string (using PHP):
echo "<script>
var employeeActions = JSON.parse('".json_encode($employeeActions)."');
</script>";
And then I get:
JSON.parse Error: Invalid character at position:33
When inspecting the page once it's loaded, here is what is echoed through my PHP script:
<script>
var employeeActions = JSON.parse('[{"template":1,"action_json":"{\"id\":\"1\",\"action\":\"An action for all of IT!\",\"date_agreed\":\"2018-08-10\",\"complete_by\":\"2018-08-31\",\"responsible_departments\":[\"8\"],\"responsible_employees\":[\"1629\",\"112\",\"1374\"],\"priority\":\"High\"}","template_json":"{\"columns\":[{\"id\":\"id\",\"title\":\"Task Number\",\"default\":true,\"type\":\"auto\"},{\"id\":\"action\",\"title\":\"Action Agreed\",\"default\":true,\"type\":\"longtext\"},{\"id\":\"date_agreed\",\"title\":\"Date Agreed\",\"default\":true,\"type\":\"date\"},{\"id\":\"complete_by\",\"title\":\"Complete By\",\"default\":true,\"type\":\"date\"},{\"id\":\"responsible_departments\",\"title\":\"Responsible Departments\",\"default\":true,\"type\":\"option\"},{\"id\":\"responsible_employees\",\"title\":\"Responsible Employees\",\"default\":true,\"type\":\"option\"},{\"id\":\"priority\",\"title\":\"Priority\",\"default\":true,\"type\":\"option\",\"options\":[\"High\",\"Medium\",\"Low\"]}]}"},{"template":1,"action_json":"{\"id\":\"1\",\"action\":\"Action numero uno\",\"date_agreed\":\"2018-08-10\",\"complete_by\":\"2018-08-10\",\"responsible_departments\":[\"8\"],\"responsible_employees\":[\"112\"],\"priority\":\"High\"}","template_json":"{\"columns\":[{\"id\":\"id\",\"title\":\"Task Number\",\"default\":true,\"type\":\"auto\"},{\"id\":\"action\",\"title\":\"Action Agreed\",\"default\":true,\"type\":\"longtext\"},{\"id\":\"date_agreed\",\"title\":\"Date Agreed\",\"default\":true,\"type\":\"date\"},{\"id\":\"complete_by\",\"title\":\"Complete By\",\"default\":true,\"type\":\"date\"},{\"id\":\"responsible_departments\",\"title\":\"Responsible Departments\",\"default\":true,\"type\":\"option\"},{\"id\":\"responsible_employees\",\"title\":\"Responsible Employees\",\"default\":true,\"type\":\"option\"},{\"id\":\"priority\",\"title\":\"Priority\",\"default\":true,\"type\":\"option\",\"options\":[\"High\",\"Medium\",\"Low\"]}]}"}]');
</script>
The text you output from json_encode will be passed through the parser for JavaScript string literals before it gets passed through JSON.parse.
Since JSON and JS string literals use the same escape characters, this will break it! You are mashing up ' characters and data to try to construct a JS string literal programmatically, but the data includes characters with special meaning in JS.
"{\"i
That shows character 33. The JS string literal \" will be parsed putting an unescaped " in the string.
Forget about using JSON.parse. Forget about trying to pass JSON to the browser. Remember that JSON and JavaScript literal syntax are more or less the same thing:
<script>
var employeeActions = <?php echo json_encode($employeeActions); ?>;
</script>
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.
Suppose I have an object variable:
var obj = {
key: '\"Hello World\"'
}
Then I tried parse it to string by using JSON.stringify in Chrome devtools console:
JSON.stringify(obj) // "{"key":"\"Hello World\""}"
I get the result "{"key":"\"Hello World\""}". Then I give it to a string
var str = '{"key":"\"Hello World\""}'
At least I try to convert it back to obj:
JSON.parse(str);
but the browser tell me wrong Uncaught SyntaxError
What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.
How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?
You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.
You need to escape the \ characters too.
var str = '{"key":"\\"Hello World\\""}'
That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.
var result = {"key":"\"Hello World\""};
try:
var str = '{"key":"\\"Hello World\\""}';
I have an ASP.NET MVC application returning a JSON string to the VIEW.
// Parsing the model returned on the VIEW
var jsonString = '#Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);
The problem is that I am not able to parse because the jsonString contains characters such as "\" and "'".
//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }
JSON is valid JavaScript, so you can just do this:
var jsonObj = #Html.Raw(Model.ToJson());
FYI, the reason the JSON parsing is failing is because the although the " are escaped with \ to make it valid JSON, the backslashes themselves need escaping in the string for them to be seen by the JSON parser. Compare:
JSON.parse('"quote: \""'); // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'
This example should also clarify what's happening to the backslashes:
var unescaped = '\"', escaped = '\\"';
console.log(unescaped, unescaped.length); // '"', 1
console.log(escaped, escaped.length); // '\"', 2
If you want to create a valid Javascript string, you need to escape backslashes and apostrophes:
var jsonString = '#Html.Raw(Model.ToJson().Replace("\\", "\\\\").Replace("'", "\\'"))';
There you go:
using Newtonsoft.Json;
JsonConvert.SerializeObject(your html string here);