Generator that writes newline-delimited json to a file and returns items
    from an iterable.
498716
def write_ndjson(filename, data_iterable, append=False, **kwargs):
    
    write_mode = "ab" if append else "wb"
    logger.info("writing to file {}".format(filename))
    with codecs.open(filename, write_mode, "utf-8") as outfile:
        for item in data_iterable:
            outfile.write(json.dumps(item) + "\n")
            yield item
961898
void writeTo(JsonGenerator generator) throws IOException {
        DeserializationState deserState = _deserState.get();

        if (deserState.isDeserialized()) {
            // Object has already been deserialized, use standard writer
            generator.writeObject(deserState.deserialized);
            return;
        }

        if (deserState.overrides.isEmpty()) {
            // With no overrides the most efficient action is to copy the original JSON verbatim.
            try {
                generator.writeRaw(deserState.json);
                return;
            } catch (UnsupportedOperationException e) {
                // Not all parsers are guaranteed to support this.  If this is one then use the default
                // generator implementation which follows.
            }
        }

        ObjectCodec codec = generator.getCodec();
        if (codec == null) {
            // No codec, defer to generator
            generator.writeObject(deserialized());
            return;
        }

        JsonParser parser = codec.getFactory().createParser(deserState.json);
        checkState(parser.nextToken() == JsonToken.START_OBJECT, "JSON did not contain an object");
        generator.writeStartObject();

        // Typically the JSON string has been pre-sorted.  Insert the overrides in order.  If it turns out the
        // JSON wasn't sorted then we'll just dump the remaining overrides at the end; it's valid JSON
        // one way or the other.

        //noinspection unchecked
        Iterator<Map.Entry<String, Object>> sortedOverrides =
                ((Map<String, Object>) OrderedJson.ordered(deserState.overrides)).entrySet().iterator();

        Map.Entry<String, Object> nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null;

        JsonToken token;
        while ((token = parser.nextToken()) != JsonToken.END_OBJECT) {
            assert token == JsonToken.FIELD_NAME;

            String field = parser.getText();
            if (deserState.overrides.containsKey(field)) {
                // There's an override for this entry; skip it
                token = parser.nextToken();
                if (token.isStructStart()) {
                    parser.skipChildren();
                }
            } else {
                // Write all overrides which sort prior to this field
                while (nextOverride != null && OrderedJson.KEY_COMPARATOR.compare(nextOverride.getKey(), field) < 0) {
                    generator.writeFieldName(nextOverride.getKey());
                    generator.writeObject(nextOverride.getValue());
                    nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null;
                }

                // Copy this field name and value to the generator
                generator.copyCurrentStructure(parser);
            }
            // Both of the above operations leave the current token immediately prior to the next
            // field or the end object token.
        }

        // Write any remaining overrides
        while (nextOverride != null) {
            generator.writeFieldName(nextOverride.getKey());
            generator.writeObject(nextOverride.getValue());
            nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null;
        }

        generator.writeEndObject();
    }
262600
def _write_json(file, contents):
    """"""
    with open(file, 'w') as f:
        return json.dump(contents, f, indent=2, sort_keys=True)
600577
function rewriteJSONFile(filePath, rewriteFile, generator) {
    const jsonObj = generator.fs.readJSON(filePath);
    rewriteFile(jsonObj, generator);
    generator.fs.writeJSON(filePath, jsonObj, null, 2);
}
879908
def write_generator_data(self, file):
        
        writer = self._get_writer(file)
        writer.writerow(["bus"] + GENERATOR_ATTRS)

        for g in self.case.generators:
            i = g.bus._i
            writer.writerow([i] + [getattr(g,a) for a in GENERATOR_ATTRS])
577827
async function generateJson(options, generatorResult) {
  const jsonPath = (
    options.jsonPath ||
    `${ path.join(options.outputDir, '/' + options.fontName) }.json`
  )

  const css = generatorResult.generateCss()
  let map = {}

  css.replace(CSS_PARSE_REGEX, (match, name, code) => map[name] = code)

  await fsAsync.writeFile(jsonPath, JSON.stringify(map, null, 4))
}
1069511
def line_iterator(readable_file, size=None):
    # type: (IO[bytes], Optional[int]) -> Iterator[bytes]
    
    read = readable_file.read
    line = []
    byte = b"1"
    if size is None or size < 0:
        while byte:
            byte = read(1)
            line.append(byte)
            if byte in b"\n":
                yield b"".join(line)
                del line[:]

    else:
        while byte and size:
            byte = read(1)
            size -= len(byte)
            line.append(byte)
            if byte in b"\n" or not size:
                yield b"".join(line)
                del line[:]
940831
def to_json(self, data):
        
        # Don't forget the empty line at the end of the file
        return (
            json.dumps(
                data,
                sort_keys=True,
                indent=4,
                separators=(",", ": "),
                default=self.json_converter,
            )
            + "\n"
        )
118813
def iterator(self):
        
        for obj in (self.execute().json().get("items") or []):
            yield self.api_obj_class(self.api, obj)
153819
def iterjson(self, *args, **kwargs):
        """"""
        from rowgenerators.rowpipe.json import VTEncoder
        import json

        if 'cls' not in kwargs:
            kwargs['cls'] = VTEncoder

        for s in self.iterstruct:
            yield (json.dumps(s, *args, **kwargs))
633463
def bulk_of_jsons(d):
    ""
    def _f(b):
        for index, item in enumerate(b):
            if item is not None:
                b[index] = d(item)
        return b
    return _f
3144
function fromJson(collection, collectionPath, next) {

  var docsBulk = [];
  var docs = fs.readdirSync(collectionPath);
  var last = ~~docs.length, counter = 0;
  if (last === 0) {
    return next(null);
  }

  docs.forEach(function(docName) {

    var doc, data;
    try {
      data = fs.readFileSync(collectionPath + docName);
    } catch (err) {
      return last === ++counter ? next(null) : null;
    }
    try {
      doc = JSON.parse(data);
    } catch (err) {
      return last === ++counter ? next(err) : error(err);
    }

    docsBulk.push({
      insertOne: {
        document: doc
      }
    });

    return last === ++counter ? collection.bulkWrite(docsBulk, next) : null;
  });
}
617260
private static TupleGenerator asGenerator( JsonObject json)
    {
    TupleGenerator tupleGenerator = new TupleGenerator();

    Optional.ofNullable( json.getJsonNumber( TUPLES_KEY))
      .ifPresent( n -> tupleGenerator.setDefaultTupleSize( n.intValue()));

    Optional.ofNullable( json.getJsonNumber( SEED_KEY))
      .ifPresent( n -> tupleGenerator.setRandomSeed( n.longValue()));

    // Get any combiners for this generator.
    Optional.ofNullable( json.getJsonArray( COMBINERS_KEY))
      .map( combiners -> combiners.getValuesAs( JsonObject.class).stream())
      .orElse( Stream.empty())
      .forEach( combiner -> tupleGenerator.addCombiner( asCombiner( combiner)));

    return tupleGenerator;
    }
151676
def write_json(dictionary, filename):
    """"""
    with open(filename, 'w') as data_file:
        json.dump(dictionary, data_file, indent=4, sort_keys=True)
    print('--> Wrote ' + os.path.basename(filename))
314233
def dict_flat_generator(value, attname=None, splitter=JSPLITTER,
                        dumps=None, prefix=None, error=ValueError,
                        recursive=True):
    ''''''
    if not isinstance(value, dict) or not recursive:
        if not prefix:
            raise error('Cannot assign a non dictionary to a JSON field')
        else:
            name = '%s%s%s' % (attname, splitter,
                               prefix) if attname else prefix
            yield name, dumps(value) if dumps else value
    else:
        # loop over dictionary
        for field in value:
            val = value[field]
            key = prefix
            if field:
                key = '%s%s%s' % (prefix, splitter,
                                  field) if prefix else field
            for k, v2 in dict_flat_generator(val, attname, splitter, dumps,
                                             key, error, field):
                yield k, v2
1203248
def extract_snow_tweets_from_file_generator(json_file_path):
    
    with open(json_file_path, "r", encoding="utf-8") as fp:
        for file_line in fp:
            tweet = json.loads(file_line)
            yield tweet
141861
def Deserializer(stream_or_string, **options):
    
    if isinstance(stream_or_string, (bytes, six.string_types)):
        stream_or_string = BytesIO(stream_or_string)
    try:
        def line_generator():
            for line in stream_or_string:
                yield json.loads(line.strip())
        for obj in PythonDeserializer(line_generator(), **options):
            yield obj
    except GeneratorExit:
        raise
    except Exception as e:
        # Map to deserializer error
        six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])