Home > other >  How to transform unquoted keys in JSON string to quoted keys in R gsub() function
How to transform unquoted keys in JSON string to quoted keys in R gsub() function

Time:08-12

I have a json string like this taken from a csv file.

"{roti:{content:4,duration:6,difficulty:5,aestheticism:5,satisfaction:6},step1:{1:2,2:3,3:4,4:5,5:0,6:4,7:6,31:3,32:5,33:5,34:1,35:3,36:6,37:4,38:3,39:5,40:5,41:1,42:5,43:4,44:3,45:5,46:6,47:0,48:4,49:2,50:4,51:6,52:5,53:4},step2:{8:3,9:0,10:2,11:4,12:6,13:5,54:1,55:2,56:3,57:1,58:2,59:3,60:0,61:1},step3:{14:2,15:4,16:6,62:3,63:2,64:2,65:5,66:6},step4:{17:3,18:3,19:1,20:4,21:6,67:1,68:2,69:2,70:4,71:4,72:5,73:6,74:5,75:4,76:3,77:2,78:1,79:0,80:2,81:6,82:5,83:4,84:5},step5:{22:2,23:4,24:5,25:1,26:2,85:1,86:0,87:2,88:5,89:3,90:6,91:1,92:0,93:5,94:4,95:3,96:1,97:2,98:3,99:4,100:4,101:5,102:6,103:2,104:1,105:4,106:3,107:2,108:1,109:6,110:0,111:4,112:5,113:4,114:3,115:5,116:4,117:6,118:0,119:3,120:4,121:2,122:4,123:3,124:5,125:6,126:4,127:3,128:4,129:5,130:6,131:4},step6:{27:5,28:3,29:6,30:5,132:1,133:0,134:3,135:4,136:6,137:2,138:1,139:5},step7:{age:1,gender:female,status:direction,diploma:aLevels,reasons:{curiosity:true}}}"

The keys are unquoted here and because of that fromJSON() function returns an error "not all data was parsed (0 chars were parsed out of a total of 932 chars)"

I want this string with quoted keys like this.

{"roti":{"content":4,"duration":6,"difficulty":5,"aestheticism":5,"satisfaction":6}

How can I do that using gsub() in R?

CodePudding user response:

You could use gsub('(\\w )', '"\\1"', json):

json <- "{roti:{content:4,duration:6,difficulty:5,aestheticism:5,satisfaction:6},step1:{1:2,2:3,3:4,4:5,5:0,6:4,7:6,31:3,32:5,33:5,34:1,35:3,36:6,37:4,38:3,39:5,40:5,41:1,42:5,43:4,44:3,45:5,46:6,47:0,48:4,49:2,50:4,51:6,52:5,53:4},step2:{8:3,9:0,10:2,11:4,12:6,13:5,54:1,55:2,56:3,57:1,58:2,59:3,60:0,61:1},step3:{14:2,15:4,16:6,62:3,63:2,64:2,65:5,66:6},step4:{17:3,18:3,19:1,20:4,21:6,67:1,68:2,69:2,70:4,71:4,72:5,73:6,74:5,75:4,76:3,77:2,78:1,79:0,80:2,81:6,82:5,83:4,84:5},step5:{22:2,23:4,24:5,25:1,26:2,85:1,86:0,87:2,88:5,89:3,90:6,91:1,92:0,93:5,94:4,95:3,96:1,97:2,98:3,99:4,100:4,101:5,102:6,103:2,104:1,105:4,106:3,107:2,108:1,109:6,110:0,111:4,112:5,113:4,114:3,115:5,116:4,117:6,118:0,119:3,120:4,121:2,122:4,123:3,124:5,125:6,126:4,127:3,128:4,129:5,130:6,131:4},step6:{27:5,28:3,29:6,30:5,132:1,133:0,134:3,135:4,136:6,137:2,138:1,139:5},step7:{age:1,gender:female,status:direction,diploma:aLevels,reasons:{curiosity:true}}}"

library(jsonlite)

fromJSON(gsub('(\\w )', '"\\1"', json))
$roti
$roti$content
[1] "4"

$roti$duration
[1] "6"

$roti$difficulty
[1] "5"

$roti$aestheticism
[1] "5"

$roti$satisfaction
[1] "6"

...
  • Related