Method: Oj::Doc.open_file

Defined in:
ext/oj/fast.c

.open_file(filename) ⇒ Object

Parses a JSON document from a file and then yields to the provided block if one is given with an instance of the Oj::Doc as the single yield parameter. If a block is not given then an Oj::Doc instance is returned and must be closed with a call to the #close() method when no longer needed.

@param [String] filename name of file that contains a JSON document

method call

Examples:

File.open('array.json', 'w') { |f| f.write('[1,2,3]') }
Oj::Doc.open_file(filename) { |doc| doc.size() }  #=> 4
# or as an alternative
doc = Oj::Doc.open_file(filename)
doc.size()  #=> 4
doc.close()

Yield Parameters:

  • doc (Oj::Doc)

    parsed JSON document

Yield Returns:

  • (Object)

    returns the result of the yield as the result of the



1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'ext/oj/fast.c', line 1122

static VALUE doc_open_file(VALUE clas, VALUE filename) {
    char          *path;
    char          *json;
    FILE          *f;
    size_t         len;
    volatile VALUE obj;
    int            given = rb_block_given_p();

    path = StringValuePtr(filename);
    if (0 == (f = fopen(path, "r"))) {
        rb_raise(rb_eIOError, "%s", strerror(errno));
    }
    fseek(f, 0, SEEK_END);
    len  = ftell(f);
    json = OJ_R_ALLOC_N(char, len + 1);

    fseek(f, 0, SEEK_SET);
    if (len != fread(json, 1, len, f)) {
        fclose(f);
        rb_raise(rb_const_get_at(Oj, rb_intern("LoadError")),
                 "Failed to read %lu bytes from %s.",
                 (unsigned long)len,
                 path);
    }
    fclose(f);
    json[len] = '\0';
    obj       = parse_json(clas, json, given);
    // TBD is this needed
    /*
    if (given) {
        OJ_R_FREE(json);
    }
    */
    return obj;
}