简体   繁体   English

如何从 json 字符串的属性中删除单引号

[英]How to remove single quotes from around the properties of a json string

I need a correct and easy way to convert a JSON String to object (javascript code string), like:我需要一种正确且简单的方法将 JSON 字符串转换为 object(javascript 代码字符串),例如:

"'attribute': {
  'attribute': 'value',
  'attribute2': 0
}"

to

"attribute: {
  attribute: 'value',
  attribute2: 0
}"

The thing is remove the ' around the attribute.事情是删除属性周围的'

The porpose of this is to help convert a object to a javascript code using the JSON.stringfy().这样做的目的是帮助使用 JSON.stringfy() 将 object 转换为 javascript 代码。

This regex can remove single quotes from around the property names.此正则表达式可以删除属性名称周围的单引号。 There will be some extreme cases that would not be working with this regex.会有一些极端情况不适用于此正则表达式。 But for simple objects as cited in your question, this is good.但是对于您的问题中引用的简单对象,这很好。

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

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