简体   繁体   中英

Adding single quotes to values in object (javascript)

I have a string like this :

"[ {name: foo, type: int}, {name: status, type: string}, 
{name: boo, type: string}, {name: koo, type: data} ]"

and i need to add single quotes for values inside every object , to become like this string :

"[ {name: 'foo', type: 'int'}, {name: 'status', type: 
'string'}, {name: 'boo', type: 'string'}, {name: 'koo', 
type: 'data'} ]"

i have tried to use eval , JSON.parse , but didn't see the expected result , is there any idea to do this and just add the single quotes for values in objects ?

This is the whole JSON , but i only need the fields part .

{
"success": true,
    "count": 1,
"data": [
    {
    "res": "extend: 'someCode', fields: [ {name: foo, type: int}, 
           {name: status, type: string}, 
           {name: boo, type: string}, {name: koo, type: data} ]"
    }     
       ]
}

Here's a way to do it with a regex:

 const val = `[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]` console.log(val.replace(/(\\w+)\\s*\\:\\s*(\\w+)/g, "$1: '$2'")) 

Seems to produce a valid javascript array:

> eval(val.replace(/(\w+)\s*\:\s*(\w+)/g, "$1: '$2'"))
[ { name: 'foo', type: 'int' },
  { name: 'status', type: 'string' },
  { name: 'boo', type: 'string' },
  { name: 'koo', type: 'data' } ]

Might have to tweak it to suit your use case.

Here are the tweaks needed to fix Richard's code

 let val = `[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]` val = val.replace(/(\\w+)\\s*\\:\\s*(\\w+)/g, "\\"$1\\": \\"$2\\"") console.log(JSON.parse(val)) 

Here is a correct JS object from the "JSON" you posted

{
  "success": "true",
    "count": 1,
    "data": [{
      "res": { "extend": "someCode" }, 
      "fields": [ 
        {"name": "foo",  "type": "int"}, 
        {"name": "status", "type": "string"}, 
        {"name": "boo", "type": "string"}, 
        {"name": "koo", "type": "data" } 
      ]
    }
  ]
}

Regexp replacement may be easy for this.

 var s = "[ {name: foo, type: int}, {name: status, type: string}, {name: boo, type: string}, {name: koo, type: data} ]"; console.log(s.replace(/:[ ]*([^ ,}]+)/gi, ": '$1'")); 

> "[ {name: 'foo', type: 'int'}, {name: 'status', type: 'string'}, {name: 'boo', type: 'string'}, {name: 'koo', type: 'data'} ]"

Please see below too.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

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