Parsing string as JSON with single quotes?

157,254

Solution 1

The 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.

Solution 2

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>

Solution 3

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()

Solution 4

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.

Solution 5

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);

This solved the problem for me.

Share:
157,254

Related videos on Youtube

Coderaemon
Author by

Coderaemon

Cartoon turned Engineer.

Updated on October 17, 2021

Comments

  • Coderaemon
    Coderaemon over 1 year

    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.

    • aup
      aup about 7 years
      Single quotes are not correctly formatted json, so if you're receiving something like that, you'd probably need to use str.replace() and replace single qoutes with " before trying to parse it
    • ReeCube
      ReeCube about 7 years
      You should anyway always try to use single quotes for strings in javascript. 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. :)
    • Dave Newton
      Dave Newton about 7 years
      @ReeCube That seems little more than an opinion--there's no problem with HTML anyway, it accepts both. For JSON, why create it with strings anyway? I don't actually recall the last time I built JSON out of anything other than an object.
  • Sterling Archer
    Sterling Archer about 5 years
    Please explain your answers
  • snedkov
    snedkov over 4 years
    Upvoted because above solutions will fail with something like: {'section': "24'"} which becomes: {"section": "24""} and won't parse.
  • jpumford
    jpumford over 4 years
    Guys, don't ever do this. This is super unsafe
  • Timothy Gonzalez
    Timothy Gonzalez over 3 years
    Your answer will tamper with data. A good answer would change the structure and not the data inside the data structure.
  • Arkanoid
    Arkanoid over 3 years
    Even if you think eval is not evil in this case, JSON.parse is always faster: jsperf.com/json-parse-vs-eval/3
  • Sam R.
    Sam R. over 3 years
    This should be the top answer.
  • DriLLFreAK100
    DriLLFreAK100 about 3 years
    Perfect solution. Was trying to scrape a JSON string from html's script tag, which contains linebreaks and empty spaces. Saved my day!
  • Jack G
    Jack G about 3 years
    The principal of using Function instead of eval is sound, but everything else is wrong. It should be var json = Function("'use strict';return " + jsonString)()
  • syockit
    syockit about 3 years
    @Arkanoid The benchmark you linked to does not apply to this case as it uses only valid JSON (due to JSON.stringify)
  • Apostolos
    Apostolos almost 3 years
    @ssube, global replacing single quotes with double ones is the first that comes to the mind and is a slipshod method, because it can destroy the dictionary values. E.g. 'title': "Mama's Friend" will become "title": "Mama"s Friend", which is of course invalid! I should downvote your reply but I am against downvoting. This comment is worth much more.
  • FoolishProtein
    FoolishProtein almost 3 years
    this will modify the data as well. {'a':"A'A"} will become {"a":"A"A"}
  • jAntoni
    jAntoni over 2 years
    For me this worked <script>JSON.stringify(some_jsonString)</script>
  • Selvam Raju about 2 years
    Hi @Apostolos I agree with you and I now face the same issue. Were you able to find a solution? Thanks in advance
  • Apostolos
    Apostolos about 2 years
    Yes, I found a solution @Selvam, but it's a long time ago but I can't remember what was it since I very rarely use JSON stuff these days. Sorry! :(
  • Selvam Raju about 2 years
    No problem. Thanks for responding @Apostolos
  • Adi Darachi
    Adi Darachi about 2 years
    Don't get the comments here. This COULD be unsafe, not unsafe in any implementation, same as many APIS!. It's funny to me that this answer got 10+ downvotes while the answer with 'eval' got 15+ vote ups when THEY ARE "UNSAFE" IN EXACTLY THE SAME WAY. When there is no chance for user input to be evaluated, there is NO RISK AT ALL! Using Function constructor for instead of 'eval', is perfectly fine, and much more elegant to do.
  • luchonacho
    luchonacho over 1 year
    How would you implement this? I'm trying to read the file in R using jsonlite package.
  • MohammadReza Abbasi
    MohammadReza Abbasi over 1 year
    👏👏👏👏 👏👏good
  • Tanmay Bairagi
    Tanmay Bairagi about 1 year
    what if a string is - {a:A}? How can we parse this?
  • Ben Dev
    Ben Dev about 1 year
    It is good to know json5 available, just learned it here :)
  • Ben Dev
    Ben Dev about 1 year
    Good points, so you can get the js object that corresponds to your data