简体   繁体   中英

javascript json parse with single quote

I am trying to transform into a json object the an object this works well with the following object and the associated code :

myStr = "{'key':'value'}"
JSON.parse(myStr.replace(/'/g, "\""));

The problem is that with the same code, I am getting an exception with the following object :

myStr = "{'key':'val'ue'}"

The error is unexpected token u. I would like to keep the single quote between l and u, and not replace it.

Is there anyway?

您可以这样做,但是感觉有点it ...

JSON.parse(myStr.replace(/{'/g, "{\"").replace(/'}/g, "\"}").replace(/':'/g, "\":\""));

Hope this may help you. Assuming the inner singe quote comes between alphabets.

myStr = "{'key':'val'ue'}"
JSON.parse(myStr.replace(/([a-z])'([a-z])/g, "$1\\'$2"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM