Class: Oj::Doc

Inherits:
Object
  • Object
show all
Defined in:
ext/oj/fast.c,
ext/oj/fast.c

Overview

The Doc class is used to parse and navigate a JSON document. The model it employs is that of a document that while open can be navigated and values extracted. Once the document is closed the document can not longer be accessed. This allows the parsing and data extraction to be extremely fast compared to other JSON parses.

An Oj::Doc class is not created directly but the _open()_ class method is used to open a document and the yield parameter to the block of the #open() call is the Doc instance. The Doc instance can be moved across, up, and down the JSON document. At each element the data associated with the element can be extracted. It is also possible to just provide a path to the data to be extracted and retrieve the data in that manner.

For many of the methods a path is used to describe the location of an element. Paths follow a subset of the XPath syntax. The slash ('/') character is the separator. Each step in the path identifies the next branch to take through the document. A JSON object will expect a key string while an array will expect a positive index. A .. step indicates a move up the JSON document.

Examples:

json = %{[
  {
    "one"   : 1,
    "two"   : 2
  },
  {
    "three" : 3,
    "four"  : 4
  }
]}
# move and get value
Oj::Doc.open(json) do |doc|
  doc.move('/1/two')
  # doc location is now at the 'two' element of the hash that is the first element of the array.
  doc.fetch()
end
#=> 2

# Now try again using a path to Oj::Doc.fetch() directly and not using a block.
doc = Oj::Doc.open(json)
doc.fetch('/2/three')  #=> 3
doc.close()

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.open(json) ⇒ Object

Parses a JSON document String 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] json JSON document string

Examples:

Oj::Doc.open('[1,2,3]') { |doc| doc.size() }  #=> 4
# or as an alternative
doc = Oj::Doc.open('[1,2,3]')
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 method call


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 1128

static VALUE
doc_open(VALUE clas, VALUE str) {
    char		*json;
    size_t		len;
    volatile VALUE	obj;
    int			given = rb_block_given_p();
    int			allocate;

    Check_Type(str, T_STRING);
    len = (int)RSTRING_LEN(str) + 1;
    allocate = (SMALL_XML < len || !given);
    if (allocate) {
	json = ALLOC_N(char, len);
    } else {
	json = ALLOCA_N(char, len);
    }
    // It should not be necessaary to stop GC but if it is not stopped and a
    // large string is parsed that string is corrupted or freed during
    // parsing. I'm not sure what is going on exactly but disabling GC avoids
    // the issue.
    rb_gc_disable();
    memcpy(json, StringValuePtr(str), len);
    obj = parse_json(clas, json, given, allocate);
    rb_gc_enable();
    if (given && allocate) {
	xfree(json);
    }
    return obj;
}

.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

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 method call


1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
# File 'ext/oj/fast.c', line 1176

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();
    int			allocate;

    Check_Type(filename, T_STRING);
    path = StringValuePtr(filename);
    if (0 == (f = fopen(path, "r"))) {
	rb_raise(rb_eIOError, "%s", strerror(errno));
    }
    fseek(f, 0, SEEK_END);
    len = ftell(f);
    allocate = (SMALL_XML < len || !given);
    if (allocate) {
	json = ALLOC_N(char, len + 1);
    } else {
	json = ALLOCA_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';
    rb_gc_disable();
    obj = parse_json(clas, json, given, allocate);
    rb_gc_enable();
    if (given && allocate) {
	xfree(json);
    }
    return obj;
}

.open(json) ⇒ Object

Parses a JSON document String 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] json JSON document string

Examples:

Oj::Doc.open('[1,2,3]') { |doc| doc.size() }  #=> 4
# or as an alternative
doc = Oj::Doc.open('[1,2,3]')
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 method call


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 1128

static VALUE
doc_open(VALUE clas, VALUE str) {
    char		*json;
    size_t		len;
    volatile VALUE	obj;
    int			given = rb_block_given_p();
    int			allocate;

    Check_Type(str, T_STRING);
    len = (int)RSTRING_LEN(str) + 1;
    allocate = (SMALL_XML < len || !given);
    if (allocate) {
	json = ALLOC_N(char, len);
    } else {
	json = ALLOCA_N(char, len);
    }
    // It should not be necessaary to stop GC but if it is not stopped and a
    // large string is parsed that string is corrupted or freed during
    // parsing. I'm not sure what is going on exactly but disabling GC avoids
    // the issue.
    rb_gc_disable();
    memcpy(json, StringValuePtr(str), len);
    obj = parse_json(clas, json, given, allocate);
    rb_gc_enable();
    if (given && allocate) {
	xfree(json);
    }
    return obj;
}

Instance Method Details

#cloneObject


1671
1672
1673
1674
1675
# File 'ext/oj/fast.c', line 1671

static VALUE
doc_not_implemented(VALUE self) {
    rb_raise(rb_eNotImpError, "Not implemented.");
    return Qnil;
}

#closeObject

Closes an open document. No further calls to the document will be valid after closing.

Examples:

doc = Oj::Doc.open('[1,2,3]')
doc.size()  #=> 4
doc.close()

1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
# File 'ext/oj/fast.c', line 1653

static VALUE
doc_close(VALUE self) {
    Doc		doc = self_doc(self);

    rb_gc_unregister_address(&doc->self);
    DATA_PTR(doc->self) = 0;
    if (0 != doc) {
	xfree(doc->json);
	doc_free(doc);
	xfree(doc);
    }
    return Qnil;
}

#dump(path, filename) ⇒ Object

Dumps the document or nodes to a new JSON document. It uses the default options for generating the JSON.

@param path [String] if provided it identified the top of the branch to dump to JSON
@param filename [String] if provided it is the filename to write the output to

Examples:

Oj::Doc.open('[3,[2,1]]') { |doc|
    doc.dump('/2')
}
#=> "[2,1]"

1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
# File 'ext/oj/fast.c', line 1589

static VALUE
doc_dump(int argc, VALUE *argv, VALUE self) {
    Doc		doc = self_doc(self);
    Leaf	leaf;
    const char	*path = 0;
    const char	*filename = 0;

    if (1 <= argc) {
	if (Qnil != *argv) {
	    Check_Type(*argv, T_STRING);
	    path = StringValuePtr(*argv);
	}
	if (2 <= argc) {
	    Check_Type(argv[1], T_STRING);
	    filename = StringValuePtr(argv[1]);
	}
    }
    if (0 != (leaf = get_doc_leaf(doc, path))) {
	volatile VALUE	rjson;

	if (0 == filename) {
	    char	buf[4096];
	    struct _out out;

	    out.buf = buf;
	    out.end = buf + sizeof(buf) - 10;
	    out.allocated = false;
	    out.omit_nil = oj_default_options.dump_opts.omit_nil;
	    oj_dump_leaf_to_json(leaf, &oj_default_options, &out);
	    rjson = rb_str_new2(out.buf);
	    if (out.allocated) {
		xfree(out.buf);
	    }
	} else {
	    oj_write_leaf_to_file(leaf, filename, &oj_default_options);
	    rjson = Qnil;
	}
	return rjson;
    }
    return Qnil;
}

#dupObject


1671
1672
1673
1674
1675
# File 'ext/oj/fast.c', line 1671

static VALUE
doc_not_implemented(VALUE self) {
    rb_raise(rb_eNotImpError, "Not implemented.");
    return Qnil;
}

#each_child(path = nil) ⇒ Object

Yields to the provided block for each immediate child node with the identified location of the JSON document as the root. The parameter passed to the block on yield is the Doc instance after moving to the child location.

@param [String] path if provided it identified the top of the branch to process the chilren of

Examples:

Oj::Doc.open('[3,[2,1]]') { |doc|
    result = []
    doc.each_value('/2') { |doc| result << doc.where? }
    result
}
#=> ["/2/1", "/2/2"]

Yield Parameters:

  • Doc (Doc)

    at the child location


1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
# File 'ext/oj/fast.c', line 1492

static VALUE
doc_each_child(int argc, VALUE *argv, VALUE self) {
    if (rb_block_given_p()) {
	Leaf		save_path[MAX_STACK];
	Doc		doc = self_doc(self);
	const char	*path = 0;
	size_t		wlen;

	wlen = doc->where - doc->where_path;
	if (0 < wlen) {
	    memcpy(save_path, doc->where_path, sizeof(Leaf) * (wlen + 1));
	}
	if (1 <= argc) {
	    Check_Type(*argv, T_STRING);
	    path = StringValuePtr(*argv);
	    if ('/' == *path) {
		doc->where = doc->where_path;
		path++;
	    }
	    if (0 != move_step(doc, path, 1)) {
		if (0 < wlen) {
		    memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
		}
		return Qnil;
	    }
	}
	if (COL_VAL == (*doc->where)->value_type && 0 != (*doc->where)->elements) {
	    Leaf	first = (*doc->where)->elements->next;
	    Leaf	e = first;

	    doc->where++;
	    do {
		*doc->where = e;
		rb_yield(self);
		e = e->next;
	    } while (e != first);
	}
	if (0 < wlen) {
	    memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
	}
    }
    return Qnil;
}

#each_leaf(path = nil) ⇒ Object

Yields to the provided block for each leaf node with the identified location of the JSON document as the root. The parameter passed to the block on yield is the Doc instance after moving to the child location.

@param [String] path if provided it identified the top of the branch to process the leaves of

Examples:

Oj::Doc.open('[3,[2,1]]') { |doc|
    result = {}
    doc.each_leaf() { |d| result[d.where?] = d.fetch() }
    result
}
#=> ["/1" => 3, "/2/1" => 2, "/2/2" => 1]

Yield Parameters:

  • Doc (Doc)

    at the child location


1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
# File 'ext/oj/fast.c', line 1416

static VALUE
doc_each_leaf(int argc, VALUE *argv, VALUE self) {
    if (rb_block_given_p()) {
	Leaf		save_path[MAX_STACK];
	Doc		doc = self_doc(self);
	const char	*path = 0;
	size_t		wlen;

	wlen = doc->where - doc->where_path;
	if (0 < wlen) {
	    memcpy(save_path, doc->where_path, sizeof(Leaf) * (wlen + 1));
	}
	if (1 <= argc) {
	    Check_Type(*argv, T_STRING);
	    path = StringValuePtr(*argv);
	    if ('/' == *path) {
		doc->where = doc->where_path;
		path++;
	    }
	    if (0 != move_step(doc, path, 1)) {
		if (0 < wlen) {
		    memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
		}
		return Qnil;
	    }
	}
	each_leaf(doc, self);
	if (0 < wlen) {
	    memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
	}
    }
    return Qnil;
}

#each_value(path = nil) ⇒ Object

Yields to the provided block for each leaf value in the identified location of the JSON document. The parameter passed to the block on yield is the value of the leaf. Only those leaves below the element specified by the path parameter are processed.

@param [String] path if provided it identified the top of the branch to process the leaf values of

Examples:

Oj::Doc.open('[3,[2,1]]') { |doc|
    result = []
    doc.each_value() { |v| result << v }
    result
}
#=> [3, 2, 1]

Oj::Doc.open('[3,[2,1]]') { |doc|
    result = []
    doc.each_value('/2') { |v| result << v }
    result
}
#=> [2, 1]

Yield Parameters:

  • val (Object)

    each leaf value


1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
# File 'ext/oj/fast.c', line 1559

static VALUE
doc_each_value(int argc, VALUE *argv, VALUE self) {
    if (rb_block_given_p()) {
	Doc		doc = self_doc(self);
	const char	*path = 0;
	Leaf		leaf;

	if (1 <= argc) {
	    Check_Type(*argv, T_STRING);
	    path = StringValuePtr(*argv);
	}
	if (0 != (leaf = get_doc_leaf(doc, path))) {
	    each_value(doc, leaf);
	}
    }
    return Qnil;
}

#fetch(path = nil) ⇒ Object

Returns the value at the location identified by the path or the current location if the path is nil or not provided. This method will create and return an Array or Hash if that is the type of Object at the location specified. This is more expensive than navigating to the leaves of the JSON document.

@param [String] path path to the location to get the type of if provided

Examples:

Oj::Doc.open('[1,2]') { |doc| doc.fetch() }      #=> [1, 2]
Oj::Doc.open('[1,2]') { |doc| doc.fetch('/1') }  #=> 1

1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
# File 'ext/oj/fast.c', line 1380

static VALUE
doc_fetch(int argc, VALUE *argv, VALUE self) {
    Doc			doc;
    Leaf		leaf;
    volatile VALUE	val = Qnil;
    const char		*path = 0;

    doc = self_doc(self);
    if (1 <= argc) {
	Check_Type(*argv, T_STRING);
	path = StringValuePtr(*argv);
	if (2 == argc) {
	    val = argv[1];
	}
    }
    if (0 != (leaf = get_doc_leaf(doc, path))) {
	val = leaf_value(doc, leaf);
    }
    return val;
}

#homeObject

Moves the document marker or location to the hoot or home position. The same operation can be performed with a Oj::Doc.move('/').

Examples:

Oj::Doc.open('[1,2,3]') { |doc| doc.move('/2'); doc.home(); doc.where? }  #=> '/'

1316
1317
1318
1319
1320
1321
1322
1323
1324
# File 'ext/oj/fast.c', line 1316

static VALUE
doc_home(VALUE self) {
    Doc	doc = self_doc(self);

    *doc->where_path = doc->data;
    doc->where = doc->where_path;

    return oj_slash_string;
}

#local_keyObject

Returns the final key to the current location.

Examples:

Oj::Doc.open('[1,2,3]') { |doc| doc.move('/2'); doc.local_key() }	    #=> 2
Oj::Doc.open('{"one":3}') { |doc| doc.move('/one'); doc.local_key() }  #=> "one"
Oj::Doc.open('[1,2,3]') { |doc| doc.local_key() }			    #=> nil

1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'ext/oj/fast.c', line 1294

static VALUE
doc_local_key(VALUE self) {
    Doc			doc = self_doc(self);
    Leaf		leaf = *doc->where;
    volatile VALUE	key = Qnil;

    if (T_HASH == leaf->parent_type) {
	key = rb_str_new2(leaf->key);
	key = oj_encode(key);
    } else if (T_ARRAY == leaf->parent_type) {
	key = LONG2NUM(leaf->index);
    }
    return key;
}

#move(path) ⇒ Object

Moves the document marker to the path specified. The path can an absolute path or a relative path.

@param [String] path path to the location to move to

Examples:

Oj::Doc.open('{"one":[1,2]') { |doc| doc.move('/one/2'); doc.where? }  #=> "/one/2"

1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
# File 'ext/oj/fast.c', line 1458

static VALUE
doc_move(VALUE self, VALUE str) {
    Doc		doc = self_doc(self);
    const char	*path;
    int		loc;

    Check_Type(str, T_STRING);
    path = StringValuePtr(str);
    if ('/' == *path) {
	doc->where = doc->where_path;
	path++;
    }
    if (0 != (loc = move_step(doc, path, 1))) {
	rb_raise(rb_eArgError, "Failed to locate element %d of the path %s.", loc, path);
    }
    return Qnil;
}

#sizeObject

Returns the number of nodes in the JSON document where a node is any one of the basic JSON components.

Examples:

Oj::Doc.open('[1,2,3]') { |doc| doc.size() }  #=> 4

Returns:

  • Returns the size of the JSON document.


1639
1640
1641
1642
# File 'ext/oj/fast.c', line 1639

static VALUE
doc_size(VALUE self) {
    return ULONG2NUM(((Doc)DATA_PTR(self))->size);
}

#type(path = nil) ⇒ Object

Returns the Class of the data value at the location identified by the path or the current location if the path is nil or not provided. This method does not create the Ruby Object at the location specified so the overhead is low.

@param [String] path path to the location to get the type of if provided

Examples:

Oj::Doc.open('[1,2]') { |doc| doc.type() }	     #=> Array
Oj::Doc.open('[1,2]') { |doc| doc.type('/1') }  #=> Fixnum

1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'ext/oj/fast.c', line 1337

static VALUE
doc_type(int argc, VALUE *argv, VALUE self) {
    Doc		doc = self_doc(self);
    Leaf	leaf;
    const char	*path = 0;
    VALUE	type = Qnil;

    if (1 <= argc) {
	Check_Type(*argv, T_STRING);
	path = StringValuePtr(*argv);
    }
    if (0 != (leaf = get_doc_leaf(doc, path))) {
	switch (leaf->rtype) {
	case T_NIL:	type = rb_cNilClass;	break;
	case T_TRUE:	type = rb_cTrueClass;	break;
	case T_FALSE:	type = rb_cFalseClass;	break;
	case T_STRING:	type = rb_cString;	break;
#ifdef RUBY_INTEGER_UNIFICATION
	case T_FIXNUM:	type = rb_cInteger;	break;
#else
	case T_FIXNUM:	type = rb_cFixnum;	break;
#endif
	case T_FLOAT:	type = rb_cFloat;	break;
	case T_ARRAY:	type = rb_cArray;	break;
	case T_HASH:	type = rb_cHash;	break;
	default:				break;
	}
    }
    return type;
}

#where?Boolean

Returns a String that describes the absolute path to the current location in the JSON document.

Returns:

  • (Boolean)

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
# File 'ext/oj/fast.c', line 1248

static VALUE
doc_where(VALUE self) {
    Doc	doc = self_doc(self);

    if (0 == *doc->where_path || doc->where == doc->where_path) {
	return oj_slash_string;
    } else {
	Leaf	*lp;
	Leaf	leaf;
	size_t	size = 3; // leading / and terminating \0
	char	*path;
	char	*p;

	for (lp = doc->where_path; lp <= doc->where; lp++) {
	    leaf = *lp;
	    if (T_HASH == leaf->parent_type) {
		size += esc_strlen((*lp)->key) + 1;
	    } else if (T_ARRAY == leaf->parent_type) {
		size += ((*lp)->index < 100) ? 3 : 11;
	    }
	}
	path = ALLOCA_N(char, size);
	p = path;
	for (lp = doc->where_path; lp <= doc->where; lp++) {
	    leaf = *lp;
	    if (T_HASH == leaf->parent_type) {
		p = append_key(p, (*lp)->key);
	    } else if (T_ARRAY == leaf->parent_type) {
		p = ulong_fill(p, (*lp)->index);
	    }
	    *p++ = '/';
	}
	*--p = '\0';

	return rb_str_new(path, p - path);
    }
}