Re-expands a flattened json representation from a collection of attributes back into a raw
nested json string.
513193
public static String toJsonString(Collection<Attribute> attributeCollection, ObjectMapper objectMapper) throws JsonProcessingException {
        return objectMapper.writeValueAsString(toObject(attributeCollection));
    }
489677
def from_json(cls, json):
    
    return cls(json[cls.BLOB_KEY_PARAM],
               json[cls.START_INDEX_PARAM],
               json[cls.END_INDEX_PARAM])
1018583
function formatsToJSON(attrs, options) {
        var defaultFormats = ['html'],
            formatsToKeep = options.formats || defaultFormats;

        // Iterate over all known formats, and if they are not in the keep list, remove them
        _.each(Post.allowedFormats, function (format) {
            if (formatsToKeep.indexOf(format) === -1) {
                delete attrs[format];
            }
        });

        return attrs;
    }
1302303
function toJSON(unfilteredOptions) {
        const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON');
        options.omitPivot = true;

        // CASE: get JSON of previous attrs
        if (options.previous) {
            const clonedModel = _.cloneDeep(this);
            clonedModel.attributes = this._previousAttributes;

            if (this.relationships) {
                this.relationships.forEach((relation) => {
                    if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) {
                        clonedModel.related(relation).models = this._previousRelations[relation].models;
                    }
                });
            }

            return proto.toJSON.call(clonedModel, options);
        }

        return proto.toJSON.call(this, options);
    }
234239
def json_repr(obj):
    

    def serialize(obj):
        """Recursively walk object's hierarchy.
        """
        if obj is None:
            return None
        if isinstance(obj, Enum):
            return str(obj)
        if isinstance(obj, (bool, int, float, str)):
            return obj
        if isinstance(obj, dict):
            obj = obj.copy()
            for key in sorted(obj.keys()):
                obj[key] = serialize(obj[key])
            return obj
        if isinstance(obj, list):
            return [serialize(item) for item in obj]
        if isinstance(obj, tuple):
            return tuple(serialize([item for item in obj]))
        if hasattr(obj, '__dict__'):
            return serialize(obj.__dict__)
        return repr(obj)

    return json.dumps(serialize(obj))
188677
def reconstruct_dict(dot_paths, values):
    
    '''  '''
    
    output_dict = {}
    
    for i in range(len(dot_paths)):
        if i + 1 <= len(values):
            path_segments = segment_path(dot_paths[i])
            current_nest = output_dict
            for j in range(len(path_segments)):
                key_name = path_segments[j]
                try:
                    key_name = int(key_name)
                except:
                    pass
                if j + 1 == len(path_segments):
                    if isinstance(key_name, int):
                        current_nest.append(values[i])
                    else:
                        current_nest[key_name] = values[i]
                else:
                    next_key = path_segments[j+1]
                    try:
                        next_key = int(next_key)
                    except:
                        pass
                    if isinstance(next_key, int):
                        if not key_name in current_nest.keys():
                            current_nest[key_name] = []
                        current_nest = current_nest[key_name]
                    else:
                        if isinstance(key_name, int):
                            current_nest.append({})
                            current_nest = current_nest[len(current_nest) - 1]
                        else:
                            if not key_name in current_nest.keys():
                                current_nest[key_name] = {}
                            current_nest = current_nest[key_name]
    
    return output_dict
1133753
def flatten_json_request_body(prefix, dict_body, spec):
    """"""
    if len(spec) == 1 and 'type' in spec:
        return {prefix: to_str(dict_body, spec)}

    flat = {}
    for key, value in dict_body.items():
        node_type = spec[key]['type']
        if node_type == 'list':
            for idx, v in enumerate(value, 1):
                pref = key + '.member.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref, v, spec[key]['member']))
        elif node_type == 'map':
            for idx, (k, v) in enumerate(value.items(), 1):
                pref = key + '.entry.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref + '.key', k, spec[key]['key']))
                flat.update(flatten_json_request_body(
                    pref + '.value', v, spec[key]['value']))
        else:
            flat.update(flatten_json_request_body(key, value, spec[key]))

    if prefix:
        prefix = prefix + '.'
    return dict((prefix + k, v) for k, v in flat.items())
1351821
function flatten(source) {
  var output = {};

  function step(object, prev) {
    for (var key in object) {
      if (has.call(object, key)) {
        var value = object[key];
        var newKey = prev ? prev + ' ' + key : key;

        if (!is.array(value) && is.object(value)) {
          return step(value, newKey);
        }

        output[newKey] = value;
      }
    }
  }

  step(source);

  return output;
}
407110
def flatatt(attrs):
    
    return _flatatt({k.replace('_', '-'): v for k, v in attrs.items()})
1224863
void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
            final boolean includeNullValuedFields, final int depth, final int indentWidth,
            final StringBuilder buf) {
        final boolean prettyPrint = indentWidth > 0;
        final int n = items.size();
        int numDisplayedFields;
        if (includeNullValuedFields) {
            numDisplayedFields = n;
        } else {
            numDisplayedFields = 0;
            for (final Entry<String, Object> item : items) {
                if (item.getValue() != null) {
                    numDisplayedFields++;
                }
            }
        }
        if (objectId == null && numDisplayedFields == 0) {
            buf.append("{}");
        } else {
            buf.append(prettyPrint ? "{\n" : "{");
            if (objectId != null) {
                // id will be non-null if this object does not have an @Id field, but was referenced by
                // another object (need to include ID_TAG)
                if (prettyPrint) {
                    JSONUtils.indent(depth + 1, indentWidth, buf);
                }
                buf.append('"');
                buf.append(JSONUtils.ID_KEY);
                buf.append(prettyPrint ? "\": " : "\":");
                JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1,
                        indentWidth, buf);
                if (numDisplayedFields > 0) {
                    buf.append(',');
                }
                if (prettyPrint) {
                    buf.append('\n');
                }
            }
            for (int i = 0, j = 0; i < n; i++) {
                final Entry<String, Object> item = items.get(i);
                final Object val = item.getValue();
                if (val != null || includeNullValuedFields) {
                    final String key = item.getKey();
                    if (key == null) {
                        // Keys must be quoted, so the unquoted null value cannot be a key
                        // (Should not happen -- JSONParser.parseJSONObject checks for null keys)
                        throw new IllegalArgumentException("Cannot serialize JSON object with null key");
                    }
                    if (prettyPrint) {
                        JSONUtils.indent(depth + 1, indentWidth, buf);
                    }
                    buf.append('"');
                    JSONUtils.escapeJSONString(key, buf);
                    buf.append(prettyPrint ? "\": " : "\":");
                    JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1,
                            indentWidth, buf);
                    if (++j < numDisplayedFields) {
                        buf.append(',');
                    }
                    if (prettyPrint) {
                        buf.append('\n');
                    }
                }
            }
            if (prettyPrint) {
                JSONUtils.indent(depth, indentWidth, buf);
            }
            buf.append('}');
        }
    }
836817
def _flatten_nested_input(v):
    
    v = copy.deepcopy(v)
    if isinstance(v["type"], dict) and v["type"]["type"] == "array":
        v["type"] = v["type"]["items"]
    else:
        assert isinstance(v["type"], (list, tuple)), v
        new_type = None
        want_null = False
        for x in v["type"]:
            if isinstance(x, dict) and x["type"] == "array":
                new_type = x["items"]
            elif isinstance(x, six.string_types) and x == "null":
                want_null = True
            else:
                new_type = x
        if want_null:
            if not isinstance(new_type, (list, tuple)):
                new_type = [new_type] if new_type is not None else []
            for toadd in ["null", "string"]:
                if toadd not in new_type:
                    new_type.append(toadd)
        assert new_type, v
        v["type"] = new_type
    return v
94066
def replace_with_json(self, json):
        ''' 

        '''
        replacement = self.from_json(json)
        replacement._destructively_move(self)
1125851
function flatten(source, opts) {
  opts = opts || {};
  var delimiter = opts.delimiter = opts.delimiter || '.';
  var o = {};
  function iterate(source, parts) {
    var k, v;
    parts = parts || [];
    for(k in source) {
      v = source[k];
      if(v && typeof v === 'object' && Object.keys(v).length) {
        iterate(v, parts.concat(k));
      }else{
        o[parts.concat(k).join(delimiter)] = v;
      }
    }
  }
  iterate(source);
  return o;
}
270732
def format_link_json(self):
        """"""
        link_json = {}
        link_json['trace_id'] = self.trace_id
        link_json['span_id'] = self.span_id
        link_json['type'] = self.type

        if self.attributes is not None:
            link_json['attributes'] = self.attributes

        return link_json
1282637
def flatten(d, parent_key='', sep='__'):
    
    # http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys
    if type(d) == list:
        flat = []
        for entry in d:
            flat.append(flatten(entry, parent_key=parent_key, sep=sep))
        return flat
    else:
        items = []
        for k, v in d.items():
            new_key = parent_key + sep + k if parent_key else k

            if isinstance(v, collectionsAbc.MutableMapping):
                items.extend(flatten(v, new_key, sep=sep).items())
            else:
                items.append((new_key, v))


        return dict(items)
217611
def from_json(cls, json):
        ''' 

        '''
        roots_json = json['roots']
        root_ids = roots_json['root_ids']
        references_json = roots_json['references']

        references = instantiate_references_json(references_json)
        initialize_references_json(references_json, references)

        doc = Document()
        for r in root_ids:
            doc.add_root(references[r])

        doc.title = json['title']

        return doc
327743
def json_to_model(self, model_name, j, validate=False):
        """"""
        if validate:
            self.api_spec.validate(model_name, j)
        return self.api_spec.json_to_model(model_name, j)