javascript - node.js search and replace an exact string in json output using variables -


i have found lot of posts show how search , replace exact string between quotes when using wild card or direct search string. when using variables in for loop having trouble getting correct syntax.

i have number of keys in json output db,

myjson = json.stringify(rowsmap); 

gives

{   "mystuff": [     {       "abc": "val_de_1",       "abcxz": "val_xc_1",       "mnabc": "val_abc_1"     },     {       "abc": "val_de_2",       "abcxz": "val_xc_2",       "mnabc": "val_abc_2"     },     {       "abc": "val_de_3",       "abcxz": "val_xc_3",       "mnabc": "val_abc_3"     } } 

now loop on json , replace of key strings using 2nd k:v pair

 (var myval in mypairs) {         myjson = myjson.replace(regexp(myval, "g"), mypairs[myval]);         ....         } 

now if values abc 777 following,

{       "mystuff": [         {           "777": "val_de_1",           "777xz": "val_xc_1",           "mn777": "val_777_1"         },         {           "777": "val_de_2",           "777xz": "val_xc_2",           "mn777": "val_777_2"         },         {           "777": "val_de_3",           "777xz": "val_xc_3",           "777bc": "val_777_3"         } } 

but want

{       "mystuff": [         {           "777": "val_de_1",           "abcxz": "val_xc_1",           "mnabc": "val_abc_1"         },         {           "777": "val_de_2",           "abcxz": "val_xc_2",           "mnabc": "val_abc_2"         },         {           "777": "val_de_3",           "abcxz": "val_xc_3",           "mnabc": "val_abc_3"         }     } 

i have seen use of brackets braces , variations of quotes before , after literal string not variable.

what efficient method processing? have been able in cluncky manner

for (var myval in mypairs) {              mynewval = "\""+myval+"\"";             mynewrep = "\""+mypairs[myval]+"\"";             myjson = myjson.replace(regexp(mynewval, "g"), mynewrep);             ....             } 

note looking solution regexp must exact string between quotes, not include quotes. idea mynewrep if string found, thereby making faster assume.

you can replace json key string /[abc]/g

this replace exact string.

some matches tried.

abc - match "abc" - match abcd - not match

http://www.regexpal.com/ - try test.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -