in CBLDatabase+Insertion.m
- (NSString*) generateRevID: (CBL_Revision*)rev
withJSON: (NSData*)json
attachments: (NSDictionary*)attachments
prevID: (NSString*) prevID

@exclude
765281
@InterfaceAudience.Private
    public static String generateRevID(byte[] json, boolean deleted, String prevID) {
        MessageDigest md5Digest;

        // Revision IDs have a generation count, a hyphen, and a UUID.

        int generation = 0;
        if (prevID != null) {
            generation = RevisionInternal.generationFromRevID(prevID);
            if (generation == 0) {
                return null;
            }
        }

        // Generate a getDigest for this revision based on the previous revision ID, document JSON,
        // and attachment digests. This doesn't need to be secure; we just need to ensure that this
        // code consistently generates the same ID given equivalent revisions.
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        // single byte - length of previous revision id
        // +
        // previous revision id
        int length = 0;
        byte[] prevIDUTF8 = null;
        if (prevID != null) {
            prevIDUTF8 = prevID.getBytes(Charset.forName("UTF-8"));
            length = prevIDUTF8.length;
        }
        if (length > 0xFF) {
            return null;
        }
        byte lengthByte = (byte) (length & 0xFF);
        byte[] lengthBytes = new byte[]{lengthByte};
        md5Digest.update(lengthBytes); // prefix with length byte
        if (length > 0 && prevIDUTF8 != null) {
            md5Digest.update(prevIDUTF8);
        }

        // single byte - deletion flag
        int isDeleted = ((deleted != false) ? 1 : 0);
        byte[] deletedByte = new byte[]{(byte) isDeleted};
        md5Digest.update(deletedByte);

        // json
        if (json != null) {
            md5Digest.update(json);
        }
        byte[] md5DigestResult = md5Digest.digest();

        String digestAsHex = Utils.bytesToHex(md5DigestResult);

        int generationIncremented = generation + 1;
        return String.format(Locale.ENGLISH, "%d-%s", generationIncremented, digestAsHex).toLowerCase();
    }
90071
def transform_jsonld(self, obj):
        """"""
        rec = copy.deepcopy(obj)
        rec.update(self.context)
        compacted = jsonld.compact(rec, self.context)
        if not self.expanded:
            return compacted
        else:
            return jsonld.expand(compacted)[0]
689042
function _getAttributesAsJson(attrs) {
  var rval = {};
  for(var i = 0; i < attrs.length; ++i) {
    var attr = attrs[i];
    if(attr.shortName && (
      attr.valueTagClass === asn1.Type.UTF8 ||
      attr.valueTagClass === asn1.Type.PRINTABLESTRING ||
      attr.valueTagClass === asn1.Type.IA5STRING)) {
      var value = attr.value;
      if(attr.valueTagClass === asn1.Type.UTF8) {
        value = forge.util.encodeUtf8(attr.value);
      }
      if(!(attr.shortName in rval)) {
        rval[attr.shortName] = value;
      } else if(forge.util.isArray(rval[attr.shortName])) {
        rval[attr.shortName].push(value);
      } else {
        rval[attr.shortName] = [rval[attr.shortName], value];
      }
    }
  }
  return rval;
}
645316
def _attach_record_as_json(mfg_event, record):
  """"""
  attachment = mfg_event.attachment.add()
  attachment.name = TEST_RECORD_ATTACHMENT_NAME
  test_record_dict = htf_data.convert_to_base_types(record)
  attachment.value_binary = _convert_object_to_json(test_record_dict)
  attachment.type = test_runs_pb2.TEXT_UTF8
1020085
public JSONObject convertToJson() {
        JSONObject buoJsonModel = new JSONObject();
        try {
            // Add all keys in plane format  initially. All known keys will be replaced with corresponding data type in the following section
            JSONObject metadataJsonObject = metadata_.convertToJson();
            Iterator<String> keys = metadataJsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                buoJsonModel.put(key, metadataJsonObject.get(key));
            }
            if (!TextUtils.isEmpty(title_)) {
                buoJsonModel.put(Defines.Jsonkey.ContentTitle.getKey(), title_);
            }
            if (!TextUtils.isEmpty(canonicalIdentifier_)) {
                buoJsonModel.put(Defines.Jsonkey.CanonicalIdentifier.getKey(), canonicalIdentifier_);
            }
            if (!TextUtils.isEmpty(canonicalUrl_)) {
                buoJsonModel.put(Defines.Jsonkey.CanonicalUrl.getKey(), canonicalUrl_);
            }
            if (keywords_.size() > 0) {
                JSONArray keyWordJsonArray = new JSONArray();
                for (String keyword : keywords_) {
                    keyWordJsonArray.put(keyword);
                }
                buoJsonModel.put(Defines.Jsonkey.ContentKeyWords.getKey(), keyWordJsonArray);
            }
            if (!TextUtils.isEmpty(description_)) {
                buoJsonModel.put(Defines.Jsonkey.ContentDesc.getKey(), description_);
            }
            if (!TextUtils.isEmpty(imageUrl_)) {
                buoJsonModel.put(Defines.Jsonkey.ContentImgUrl.getKey(), imageUrl_);
            }
            if (expirationInMilliSec_ > 0) {
                buoJsonModel.put(Defines.Jsonkey.ContentExpiryTime.getKey(), expirationInMilliSec_);
            }
            buoJsonModel.put(Defines.Jsonkey.PublicallyIndexable.getKey(), isPublicallyIndexable());
            buoJsonModel.put(Defines.Jsonkey.LocallyIndexable.getKey(), isLocallyIndexable());
            buoJsonModel.put(Defines.Jsonkey.CreationTimestamp.getKey(), creationTimeStamp_);
            
        } catch (JSONException ignore) {
        }
        return buoJsonModel;
    }
1082790
function toJSON(d) {
    if (!_.isString(d)) {
        d = JSON.stringify(d);
    }

    return d;
}
275035
function jsonToMm(data) {
    startMap();
    traverseTree( data.map.node, startTag, endTag );
    endMap();
}
1123867
private void writeOnDisk(JSONObject plistJSON, File destination)
      throws IOException, JSONException {
    if (destination.exists()) {
      // This is possible if we start with capability "reuseContentAndSettings"
      log.info(destination + " already exists. Overwriting data");
    }

    // make sure the folder is ready for the plist file
    destination.getParentFile().mkdirs();

    checkPlUtil();

    File from = createTmpFile(plistJSON);

    List<String> command = new ArrayList<>();
    command.add(PLUTIL);
    command.add("-convert");
    command.add("binary1");
    command.add("-o");
    command.add(destination.getAbsolutePath());
    command.add(from.getAbsolutePath());

    ProcessBuilder b = new ProcessBuilder(command);
    int i;
    try {
      Process p = b.start();
      i = p.waitFor();
    } catch (Exception e) {
      throw new WebDriverException("failed to run " + command.toString(), e);
    }
    if (i != 0) {
      throw new WebDriverException("conversion to binary plist failed. exitCode=" + i);
    }
  }
561029
function toMetaString(obj) {
  var attrs = _.map(obj, function(_v, _k) {
    return _k + '="' + _.escape(_v) + '"';
  });

  var res = _.compact(attrs).join(" ");
  return res ? "<meta " + res + ">" : "";
}
71026
function (versionString, cb) {
      var mem = new MemoryStream(null, {readable: false});
      var url = 'https://wiseplat.github.io/solc-bin/bin/soljson-' + versionString + '.js';
      https.get(url, function (response) {
        if (response.statusCode !== 200) {
          cb(new Error('Error retrieving binary: ' + response.statusMessage));
        } else {
          response.pipe(mem);
          response.on('end', function () {
            cb(null, setupMethods(requireFromString(mem.toString(), 'soljson-' + versionString + '.js')));
          });
        }
      }).on('error', function (error) {
        cb(error);
      });
    }
1079373
public AutoBuffer writeUnwrappedJSON( AutoBuffer ab ) {
    if (is_array) {
      if (t.equals("B"))
        return ab.putJSONA4(i_ar); // NOTE: upcast
      else if (t.equals("I"))
        return ab.putJSONA4(i_ar);
      else if (t.equals("L"))
        return ab.putJSONA8(l_ar);
      else if (t.equals("F"))
        return ab.putJSONA4f(f_ar);
      else if (t.equals("D"))
        return ab.putJSONA8d(d_ar);
      else if (t.equals("Bo"))
        return ab.putJSONAStr(null); // TODO: BROKEN
      else if (t.equals("S"))
        return ab.putJSONAStr(s_ar);
      else if (t.equals("E"))
        return ab.putJSONAStr(e_ar);
      else if (t.equals("K"))
        return ab.putJSONA(k_ar);
      else if (t.equals("Iced"))
        return ab.putJSONA(iced_ar);
    } else {
      if (t.equals("B"))
        return ab.putJSON1((byte)i);
      else if (t.equals("I"))
        return ab.putJSON4(i);
      else if (t.equals("L"))
        return ab.putJSON8(l);
      else if (t.equals("F"))
        return ab.putJSON4f(f);
      else if (t.equals("D"))
        return ab.putJSON8d(d);
      else if (t.equals("Bo"))
        return ab.putJSONStrUnquoted(b ? "true" : "false");
      else if (t.equals("S"))
        return ab.putJSONName(s);
      else if (t.equals("E"))
        return ab.putJSONName(e);
      else if (t.equals("K"))
        return ab.putJSON(k);
    }

    throw H2O.fail("Unhandled type: " + t);
    // TODO: arrays
  }
448583
@InterfaceAudience.Private
    public void insertDownloads(final List<RevisionInternal> downloads) {
        Log.d(TAG, this + " inserting " + downloads.size() + " revisions...");
        final long time = System.currentTimeMillis();
        Collections.sort(downloads, getRevisionListComparator());
        db.runInTransaction(new TransactionalTask() {
            @Override
            public boolean run() {
                boolean success = false;
                try {
                    for (RevisionInternal rev : downloads) {
                        long fakeSequence = rev.getSequence();
                        List<String> history = db.parseCouchDBRevisionHistory(rev.getProperties());
                        if (history.isEmpty() && rev.getGeneration() > 1) {
                            Log.w(TAG, "%s: Missing revision history in response for: %s", this, rev);
                            setError(new CouchbaseLiteException(Status.UPSTREAM_ERROR));
                            continue;
                        }

                        Log.v(TAG, "%s: inserting %s %s", this, rev.getDocID(), history);

                        // Insert the revision
                        try {
                            db.forceInsert(rev, history, remote);
                        } catch (CouchbaseLiteException e) {
                            if (e.getCBLStatus().getCode() == Status.FORBIDDEN) {
                                Log.i(TAG, "%s: Remote rev failed validation: %s", this, rev);
                            } else if (e.getCBLStatus().getCode() == Status.BAD_ATTACHMENT) {
                                // Revision with broken _attachments metadata (i.e. bogus revpos)
                                // should not stop replication. Warn and skip it. (iOS #1001)
                                Log.w(TAG, "%s: Revision %s has invalid attachment metadata: %s", this, rev, rev.getAttachments());
                            } else {
                                Log.w(TAG, "%s: failed to write %s: status=%s",
                                        this, rev, e.getCBLStatus().getCode());
                                setError(new RemoteRequestResponseException(e.getCBLStatus().getCode(), null));
                                continue;
                            }
                        }

                        // NOTE: calling Body.compact() here cause another JSON serialization by Jackson.
                        //       At this point Body.json is null, and Body.object has values.

                        // Mark this revision's fake sequence as processed:
                        pendingSequences.removeSequence(fakeSequence);
                    }

                    Log.v(TAG, "%s: finished inserting %d revisions", this, downloads.size());
                    success = true;
                } catch (SQLException e) {
                    Log.e(TAG, this + ": Exception inserting revisions", e);
                } finally {
                    if (success) {
                        // Checkpoint:
                        setLastSequence(pendingSequences.getCheckpointedValue());

                        long delta = System.currentTimeMillis() - time;
                        Log.v(TAG,
                                "%s: inserted %d revs in %d milliseconds",
                                this, downloads.size(), delta);

                        int newCompletedChangesCount = getCompletedChangesCount().get() + downloads.size();
                        Log.d(TAG,
                                "%s insertDownloads() updating completedChangesCount from %d -> %d ",
                                this, getCompletedChangesCount().get(), newCompletedChangesCount);

                        addToCompletedChangesCount(downloads.size());
                    }
                    pauseOrResume();
                    return success;
                }
            }
        });
    }
727577
def asjsonld(self):
        """"""
        source = {}
        if self.__source__:
            source.update(self.__source__)
        source.update(asjsonld(self))
        return source
474279
def jsondump(model, fp):
    '''
    
    '''
    fp.write('[')
    links_ser = []
    for link in model:
        links_ser.append(json.dumps(link))
    fp.write(',\n'.join(links_ser))
    fp.write(']')
128394
def get_video_json(video):
    

    return json.dumps({
        'id': video.id,
        'edit_link': reverse('wagtailvideos:edit', args=(video.id,)),
        'title': video.title,
        'preview': {
            'url': video.thumbnail.url if video.thumbnail else '',
        }
    })
100395
function pprintSEXP(formJson, opts, indentLevel, priorNodeStr) {
  opts = opts || {};
  opts.lbracket = "(";
  opts.rbracket = ")";
  opts.separator = " ";
  opts.bareSymbols = true;
  return pprintJSON(formJson, opts, indentLevel, priorNodeStr);
}
1212090
function attrToJson(v, objectType) {

        var colValue;

        switch (objectType) {
            case "Text":
                colValue = v;
                break;
            case "DateTime":
            case "datetime": // For calculated columns, stored as datetime;#value
                // Dates have dashes instead of slashes: ows_Created="2009-08-25 14:24:48"
                colValue = dateToJsonObject(v);
                break;
            case "User":
                colValue = userToJsonObject(v);
                break;
            case "UserMulti":
                colValue = userMultiToJsonObject(v);
                break;
            case "Lookup":
                colValue = lookupToJsonObject(v);
                break;
            case "LookupMulti":
                colValue = lookupMultiToJsonObject(v);
                break;
            case "Boolean":
                colValue = booleanToJsonObject(v);
                break;
            case "Integer":
                colValue = intToJsonObject(v);
                break;
            case "Counter":
                colValue = intToJsonObject(v);
                break;
            case "MultiChoice":
                colValue = choiceMultiToJsonObject(v);
                break;
            case "Number":
            case "Currency":
            case "float": // For calculated columns, stored as float;#value
                colValue = floatToJsonObject(v);
                break;
            case "Calculated":
                colValue = calcToJsonObject(v);
                break;
            case "Attachments":
                colValue = attachmentsToJsonObject(v);
                break;
            case "URL":
                colValue = urlToJsonObject(v);
                break;
            case "JSON":
                colValue = jsonToJsonObject(v); // Special case for text JSON stored in text columns
                break;
            default:
                // All other objectTypes will be simple strings
                colValue = v;
                break;
        }
        return colValue;
    }