admin管理员组文章数量:1131471
I have a string
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
This seems like a simple parsing. It's not working though.
I have a string
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
This seems like a simple parsing. It's not working though.
Share Improve this question edited Feb 14, 2024 at 16:30 phuzi 13.1k4 gold badges28 silver badges59 bronze badges asked Mar 16, 2016 at 14:23 CoderaemonCoderaemon 3,8577 gold badges30 silver badges52 bronze badges 9 | Show 4 more comments13 Answers
Reset to default 125The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"')
and you should end up with valid JSON.
I know it's an old post, but you can use JSON5 for this purpose.
<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
Source:
If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.
var str = "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);
This solved the problem for me.
// regex uses look-forwards and look-behinds to select only single-quotes that should be selected
const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g;
str = str.replace(regex, '"');
str = JSON.parse(str);
The other answers simply do not work in enough cases. Such as the above cited case: "title": "Mama's Friend"
, it naively will convert the apostrophe unless you use regex. JSON5 will want the removal of single quotes, introducing a similar problem.
Warning: although I believe this is compatible with all situations that will reasonably come up, and works much more often than other answers, it can still break in theory.
Something like this:
var div = document.getElementById("result");
var str = "{'a':1}";
str = str.replace(/\'/g, '"');
var parsed = JSON.parse(str);
console.log(parsed);
div.innerText = parsed.a;
<div id="result"></div>
sometimes you just get python data, it looks a little bit like json but it is not. If you know that it is pure python data, then you can eval these data with python and convert it to json like this:
echo "{'a':1}" | /usr/bin/python3 -c "import json;print(json.dumps(eval(input())))"
Output:
{"a": 1}
this is good json.
if you are in JavaScript, then you could use JSON.stringify
like this:
data = {'id': 74,'parentId': null};
console.log(JSON.stringify(data));
Output:
> '{"id":74,"parentId":null}'
If your api throws errors unless your JSON double quotes are escaped ("{"foo": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))
newFaqJsonUpdate = JSON.stringify(JSON.stringify(faqJsonUpdate));
Add an escape for your double quotes like the following:
str = "{\"a\":1}";
JSON.parse(str);
console.log(str)
A little late to the party - but this is what helped me (Python)
Import Json - Python has the built-in module json, which allows us to work with JSON data.
import json
Print the JSON data with indentation
print(json.dumps(str_json_data, indent=4))
Write the JSON data in a file
with open("test.json", "w") as file:
file.write(json.dumps(str_json_data, indent=4))
If you assume that the single-quoted values are going to be displayed, then instead of this:
str = str.replace(/\'/g, '"');
you can keep your display of the single-quote by using this:
str = str.replace(/\'/g, '\'\');
which is the HTML equivalent of the single quote
.
json = ( new Function("return " + jsonString) )();
本文标签: javascriptParsing string as JSON with single quotesStack Overflow
版权声明:本文标题:javascript - Parsing string as JSON with single quotes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736768472a1951955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
var str = "bad example";
is not good practice, better do the following:var str = 'good example';
=> like this you won't have any problems with JSON and you wont have any problems with HTML either. :) – ReeCube Commented Mar 16, 2016 at 14:30