[英]How to add single quotes around the data-setup value that contains a JSON string that must use double quotes?
[英]How to remove single quotes from around the properties of a json string
我需要一種正確且簡單的方法將 JSON 字符串轉換為 object(javascript 代碼字符串),例如:
"'attribute': {
'attribute': 'value',
'attribute2': 0
}"
至
"attribute: {
attribute: 'value',
attribute2: 0
}"
事情是刪除屬性周圍的'
。
這樣做的目的是幫助使用 JSON.stringfy() 將 object 轉換為 javascript 代碼。
此正則表達式可以刪除屬性名稱周圍的單引號。 會有一些極端情況不適用於此正則表達式。 但是對於您的問題中引用的簡單對象,這很好。
var jsonstr = "{ 'attribute': 'value', 'attribute2': 0, 'parentattr': {'x': 0}} "; jsonstr = jsonstr.replace(/'([^']+)':/g, '$1:'); console.log(jsonstr);
JSON text/object can be converted into Javascript object using the function JSON.parse()
var object = JSON.parse('{"attribute":value, "attribute2":0}');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.