parsing - Ruby best way to make this string an array? -


what best way make string looks array of hashes real array?

the string looks this: [{name:"lol", age:12},{name:"lmao", age:66},{name: "roflcopter", age:99}] , need same array.

input: (a string)

'[{name:"lol", age:12},{name:"lmao", age:66},{name: "roflcopter", age:99}]' 

expected output: (an array of hashes)

[{name:"lol", age:12},{name:"lmao", age:66},{name: "roflcopter", age:99}] 

your string similar to, not quite same json. means have 3 choices.


1) convert json (upstream)

the difference between string , proper json string in json, keys need wrapped in quotes. if have control on format of string, suggest change in json format:

'[{"name":"lol", "age":12},{"name":"lmao", "age":66},{"name": "roflcopter", "age":99}]' 

once string in format, can turn array of hashes using json.parse:

require "json" source_string = '[{"name":"lol", "age":12},{"name":"lmao", "age":66},{"name": "roflcopter", "age":99}]' data = json.parse source_string puts data[0] #=> {"name"=>"lol", "age"=>12} 

i highly recommend course of action. included json parser handles string validation in secure way. moreover, json designed providing arrays , hashes in string form. well-accepted standard people understand.


2) convert json (downstream)

if reason cannot update source string json default (maybe you're working third party refuses adopt better standard), can programmatically modify string in proper json format. went ahead , wrote regex put proper quotes around string:

source_string = '[{name:"lol", age:12},{name:"lmao", age:66},{name: "roflcopter", age:99}]' json_string = source_string.gsub /(?<=[{,])\s*(\w+)(?=:)/, '"\1"' data = json.parse json_string puts data[0] #=> {"name"=>"lol", "age"=>12} 

3) use eval

your string, in current format, valid ruby code. means can use eval execute ruby code:

data = eval('[{name:"lol", age:12},{name:"lmao", age:66},{name: "roflcopter", age:99}]') puts data[0] #=>{name: "lol", age: 12} 

the issue eval, , reason , many other people advise against it, it's incredibly insecure. said data coming post request- if user happens modify request send string "system('rm *')", code execute:

eval("system('rm *')") 

which, may have guessed, wipe harddrive. can try write string validation make sure string safe before running eval, sort of validation not easy task, , eval weakest point in code, security standpoint.

honestly, there's no reason should this, since option #2 wonderfully straight-forward. mention know avoid it.


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 -