json-editor icon indicating copy to clipboard operation
json-editor copied to clipboard

dollar sign `$` is not allowed for with mongodb field names

Open wxs77577 opened this issue 8 years ago • 3 comments

can you use others sign instead dollar sign? I can't save a json schema data with $ref to mongodb

wxs77577 avatar Sep 05 '17 10:09 wxs77577

I've worked around it using mongoose hooks like these:

robotSchema.pre('findOneAndUpdate', function(next) {
  // Replace JSON schema's `$ref` properties with `__ref` because they conflict
  // with MongoDB `$ref` properties.
  if (this._update.paramsSchema)
    this._update.paramsSchema = replaceInKeys(this._update.paramsSchema, /^\$/, '__');

  if (this._update.settingsSchema)
    this._update.settingsSchema = replaceInKeys(this._update.settingsSchema, /^\$/, '__');

  next();
});

robotSchema.post('init', function() {
  // Replace JSON schema's `__ref` properties back to `$ref`.
  if (this.settingsSchema)
    this.settingsSchema = replaceInKeys(this.settingsSchema, /^__/, '$');

  if (this.paramsSchema)
    this.paramsSchema = replaceInKeys(this.paramsSchema, /^__/, '$');
});

function replaceInKeys(obj, regexp, replacer) {
  obj = Object.assign({}, obj);

  for (let [key, val] of Object.entries(obj)) {
    if (regexp.test(key)) {
      let oldKey = key;
      key = oldKey.replace(regexp, replacer);
      obj[key] = obj[oldKey];
      delete obj[oldKey];
    }

    // If value is an object, recursively go through its keys.
    if (typeof val === 'object') {
      // Watch out for arrays. Iterate over it's values and make replacements
      // only in objects, leaving as is strings, numbers and other types.
      if (Array.isArray(val)) {
        val = val.map(function(item) {
          if (typeof item === 'object') return replaceInKeys(item, regexp, replacer);
          else return item;
        });
        obj[key] = val;
      } else {
        obj[key] = replaceInKeys(val, regexp, replacer);
      }
    }
  }

  return obj;
}

cyxou avatar Sep 21 '17 14:09 cyxou

It works but I hope you can add a feature to custom a prefix to replace dollar sign, e.g.

var editor = new JSONEditor(element, {
  //...
  theme: 'bootstrap3',
  prefix: '__' // default is '$'
});

Thanks a lot.

wxs77577 avatar Sep 22 '17 04:09 wxs77577

It is not working for me. Is anything changed afterward? I am getting some serialization errors before the code reaching the 'pre' hook.

rejeevd avatar Jul 12 '21 14:07 rejeevd