Skip to content

Instantly share code, notes, and snippets.

@baudehlo
Created April 30, 2014 19:23
Show Gist options
  • Save baudehlo/22ccc50cd6232802cffb to your computer and use it in GitHub Desktop.
Save baudehlo/22ccc50cd6232802cffb to your computer and use it in GitHub Desktop.
"use strict";
var pattern = '("(?:\\\\\"|[^"])*?")\\s*=>\\s*((?:"(?:\\\\\"|[^"])*?")|NULL)';
var re = new RegExp(pattern,'gi');
exports.json_to_hstore = function json_to_hstore (json) {
if (typeof json == 'string') json = JSON.parse(json);
var hstore = [];
for (var key in json) {
var value = json[key];
value = value === null ? 'NULL' : JSON.stringify(value.toString());
hstore.push('"' + key + '" => ' + value);
}
return hstore.join(', ');
}
exports.hstore_to_json = function hstore_to_json (string) {
var key, value;
var result = {};
var match = null;
while((match = re.exec(val)) != null) {
key = JSON.parse(match[1]);
value = match[2] == "NULL" ? null : JSON.parse(match[2]);
result[key] = value;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment