Check out this CoffeeScript solution utilizing the underscore library. If you're not using underscore, you can easily swap _.foldl with a for loop.
alterJsonStructure = (value) ->
inQuotes = false
correctQuotationMarks = (memo, nextCharacter) ->
insertQuote =
(inQuotes and not /[a-z0-9_"]/.test nextCharacter) or
(!inQuotes and /[a-z_]/.test nextCharacter)
inQuotes = (inQuotes != (insertQuote or nextCharacter == '"') )
memo + (if insertQuote then '"' else '') + nextCharacter
valueWithQuotes = _.foldl(value + '\n', correctQuotationMarks, "")
JSON.parse(valueWithQuotes)
Alternatively, here's the same function but written in JavaScript:
function alterJsonStructure(value) {
var correctQuotationMarks, inQuotes, valueWithQuotes;
inQuotes = false;
correctQuotationMarks = function(memo, nextCharacter) {
var insertQuote;
insertQuote = (inQuotes && !/[a-z0-9_"]/.test(nextCharacter)) || (!inQuotes && /[a-z_]/.test(nextCharacter));
inQuotes = inQuotes !== (insertQuote || nextCharacter === '"');
return memo + (insertQuote ? '"' : '') + nextCharacter;
};
valueWithQuotes = _.foldl(value + '\n', correctQuotationMarks, "");
return JSON.parse(valueWithQuotes);
};