Provide utilities converting between JSON text and numeric types.
More...
Detailed Description
- Outline
-
-
- Purpose:
- Provide utilities converting between JSON text and numeric types.
-
- Classes:
-
-
- Description:
- This component provides a struct,
bdljsn::NumberUtil
, that is a namespace for a suite of functions for working with the JSON number text format. bdljsn::NumberUtil
provides a function isValidNumber
to determine whether a string is a valid JSON number. Many of the other operations in this component have, as a precondition, that isValidNumber
is true
for the text. For information about the JSON number specification and additional background on the behavior of numbers in bdljsn
see {bdljsn_jsonnumber}.
- Many of the operations in this component have
isValidNumber
as a precondition in order to provide simpler and more efficient implementations. In the context of JsonNumber
, the text will always be validated prior to performing other operations.
-
- Usage:
- This section illustrates intended use of this component.
-
- Example 1: Interpretting a JSON Number String:
- This example demonstrates using
bdljsn::NumberUtil
to work with a JSON number string. Imagine we are given and array of strings for numbers we expect to be integers, for each string we want to render some properties for that number.
- First, we define an interesting set of example data:
const char *EXAMPLE_DATA[] = {
"NaN",
"INF",
"1",
"1.5",
"-9223372036854775809",
"1.5e27",
};
const int NUM_DATA = sizeof(EXAMPLE_DATA) / sizeof(*EXAMPLE_DATA);
Then, for each number, we first check whether it is a valid JSON Number (note that the behavior for the other methods is undefined unless the text is a valid JSON Number): for (int i = 0; i < NUM_DATA; ++i) {
const char *EXAMPLE = EXAMPLE_DATA[i];
bsl::cout << "\"" << EXAMPLE << "\": " << bsl::endl;
if (!bdljsn::NumberUtil::isValidNumber(EXAMPLE)) {
bsl::cout << " * is NOT a JSON Number" << bsl::endl;
continue;
}
Next we verify that the number is an integer. This will return an accurate result even when the integer cannot be represented. Finally, we convert that number to an integer: This will output the text: "NaN":
is NOT a JSON Number
"INF":
is NOT a JSON Number
"1":
is an integer
value: 1
"1.5":
is not an integer
value: 1 (truncated)
"-9223372036854775809":
is an integer
value: -9223372036854775808 (underflow)
"1.5e27":
is an integer
value: 9223372036854775807 (overflow)