Data conversion

How to convert data to commonly used formats.

Key takeaways

Convert Library in the Commons module that contains data conversion components.
ArrayConverter Provides methods to create an array from a set of values.
BooleanConverter Provides methods to convert a value into a Boolean.
DateTimeConverter Provides methods to convert a value into a Date.
DoubleConverter Provides methods to convert a value into a double.
FloatConverter Provides methods to convert a value into a float.
IntegerConverter Provides methods to convert a value into an integer.
LongConverter Provides methods to convert a value into a long.
StringConverter Provides methods to convert a value into a string.
JsonConverter Provides methods to convert a value from/into a JSON string.
MapConverter Provides methods to convert a value into a map.
RecursiveMapConverter Provides methods to convert a value into a map in a recursive manner.
TypeConverter Provides methods to convert a value into an object specified by a type code and to get the type code of an object.

Introduction

This tutorial will help you to understand the different conversion components available in the Pip.Services toolkit, Commons module, convert library. The tutorial consists of a brief explanation of each class and its methods followed by a set of examples that show how to use each of them.

Convertors

This section contains a brief description of each class and its methods.

1) ArrayConverter

This class provides methods to create an array from a set of values. Its methods are summarized in the table and examples below.

Method Description
to_array Converts a value into an array object with an empty array as default. Single values are converted into arrays with a single element.
to_array_with_default Converts a value into an array object with a specified default. Single values are converted into arrays with a single element.
list_to_array Converts a list into an array object, with an empty array as default. Strings with comma-delimited values are split into an array of strings.
to_nullable_array Converts a value into an array object. Single values are converted into arrays with a single element.
import { ArrayConverter } from "pip-services4-commons-node"

let value1 = ArrayConverter.toArray([1, 2]);                // Returns [1, 2]
let value2 = ArrayConverter.toArray(1);                     // Returns [1]
let value3 = ArrayConverter.toArrayWithDefault(null, [1]);  // Returns [1]
let value4 = ArrayConverter.listToArray("1,2,3");           // Returns ['1', '2', '3']
let value5 = ArrayConverter.toNullableArray("1,2");         // Returns ['1,2']
Not available
// Array converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.ArrayConverter.ToArray([]int{1, 2}) // Returns [1, 2]
	value2 := convert.ArrayConverter.ToArray(1)           // Returns [1]

	defaultValue := make([]interface{}, 0)
	defaultValue = append(defaultValue, 1)

	value3 := convert.ArrayConverter.ToArrayWithDefault(nil, defaultValue) // Returns [1]
	value4 := convert.ArrayConverter.ListToArray("1,2,3")                  // Returns ['1', '2', '3']
	value5, err := convert.ArrayConverter.ToNullableArray("1,2")                // Returns ['1,2']

}
Not available
# Array converter

from pip_services4_commons.convert import ArrayConverter

value1 = ArrayConverter.to_array([1, 2])       # Returns [1, 2]
value2 = ArrayConverter.to_array(1)            # Returns [1]
value3 = ArrayConverter.to_array_with_default(None,[1])      # Returns [1]
value4 = ArrayConverter.list_to_array("1,2,3")               # Returns ['1', '2', '3']
value5 = ArrayConverter.to_nullable_array('1,2')             # Returns ['1,2']

Not available

2) BooleanConverter

This class can be used to convert different values to Boolean values using extended conversion rules. The rules and methods provided by this class are summarized in the tables and examples below.

Conversion rules
Number <> 0 are true, = 0 are false.
String "true", "yes", "T", "Y", "1" are true; "false", "no", "F", "N" are false.
DateTime <> 0 total milliseconds are true, = 0 are false.
Method Description
to_boolean Converts a value into a boolean or returns false when the conversion is not possible.
to_boolean_with_default Converts a value into a boolean or returns a default value when the conversion is not possible.
to_nullable_boolean Converts value into a boolean or returns None when the conversion is not possible.
import { BooleanConverter } from "pip-services4-commons-node"

let value1 = BooleanConverter.toBoolean("yes");                     // Returns True
let value2 = BooleanConverter.toBooleanWithDefault(true, false);    // Returns True
let value3 = BooleanConverter.toBooleanWithDefault(123, false);     // Returns True
let value4 = BooleanConverter.toNullableBoolean(true);              // Returns True
let value5 = BooleanConverter.toNullableBoolean("yes");             // Returns True
let value6 = BooleanConverter.toNullableBoolean(123);               // Returns True
let value7 = BooleanConverter.toNullableBoolean({});                // Returns null
Not available
// Boolean converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.BooleanConverter.ToBoolean("yes")                          // Returns True
	value2 := convert.BooleanConverter.ToBooleanWithDefault(true, false)         // Returns True
	value3 := convert.BooleanConverter.ToBooleanWithDefault(123, false)          // Returns False
	value4, err := convert.BooleanConverter.ToNullableBoolean(true)                  // Returns True
	value5, err := convert.BooleanConverter.ToNullableBoolean("yes")                 // Returns True
	value6, err := convert.BooleanConverter.ToNullableBoolean(123)                    // Returns nil
	value7, err := convert.BooleanConverter.ToNullableBoolean(make([]interface{}, 0)) // Returns nil
}
Not available
# Boolean converter

from pip_services4_commons.convert import BooleanConverter

value1 = BooleanConverter.to_boolean("yes")            # Returns True
value2 = BooleanConverter.to_boolean_with_default(True, False)     # Returns True   
value3 = BooleanConverter.to_boolean_with_default(123, False)      # Returns False
value4 = BooleanConverter.to_nullable_boolean(True)    # Returns True
value5 = BooleanConverter.to_nullable_boolean("yes")   # Returns True
value6 = BooleanConverter.to_nullable_boolean(123)     # Returns None
value7 = BooleanConverter.to_nullable_boolean({})      # Returns None

Not available

3) DateTimeConverter

This class can be used to convert arbitrary values into Date values using extended conversion rules. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
String Converts using the ISO time format.
Number Converts using milliseconds since Unix epoch.
Method Description
to_datetime Converts a value into Date or returns the current date when the conversion is not possible.
to_date_time_with_default Converts a value into Date or returns a default date when the conversion is not possible.
to_nullable_date_time Converts a value into Date or returns None when the conversion is not possible.
import { DateTimeConverter } from "pip-services4-commons-node"

let value0 = DateTimeConverter.toDateTime("2021-11-09T17:24:50.750Z");          // Returns 2021-11-09 17:24:50.75
let value1 = DateTimeConverter.toNullableDateTime("ABC");                       // Returns null
let value2 = DateTimeConverter.toNullableDateTime("2021-11-09T17:24:50.750Z");  // Returns 2021-11-09 17:24:50.75
let value3 = DateTimeConverter.toNullableDateTime(12345657755000);              // Returns 2361-03-21 16:22:35
let value4 = DateTimeConverter.toDateTimeWithDefault("ABC", new Date());        // Returns current datetime
let value5 = DateTimeConverter.toDateTimeWithDefault("2021-11-09T17:24:50.750Z", new Date()); // Returns 2021-11-09 17:24:50.75

Not available
// Date time converter

// Returns 2021-11-09 17:24:50.75
value0 := convert.DateTimeConverter.ToDateTime("2021-11-09T17:24:50.750Z")

// Returns nil
value1, err := convert.DateTimeConverter.ToNullableDateTime("ABC")

// Returns 2021-11-09 17:24:50.75
value2, err := convert.DateTimeConverter.ToNullableDateTime("2021-11-09T17:24:50.750Z")

// Returns 2361-03-21 16:22:35
value3, err := convert.DateTimeConverter.ToNullableDateTime(12345657755000)

// Returns current datetime
value4 := convert.DateTimeConverter.ToDateTimeWithDefault("ABC", time.Now())

// Returns 2021-11-09 17:24:50.75
value5 := convert.DateTimeConverter.ToDateTimeWithDefault("2021-11-09T17:24:50.750Z", time.Now())
Not available
# Date time converter

from pip_services4_commons.convert import DateTimeConverter
from datetime import date

value1 = DateTimeConverter.to_datetime("2021-11-09T17:24:50.750Z")              # Returns 2021-11-09 17:24:50.75
value2 = DateTimeConverter.to_nullable_datetime("ABC")                          # Returns None
value3 = DateTimeConverter.to_nullable_datetime("2021-11-09T17:24:50.750Z")     # Returns 2021-11-09 17:24:50.75
value4 = DateTimeConverter.to_nullable_datetime(12345657755000)                 # Returns 2361-03-21 16:22:35
value5 = DateTimeConverter.to_datetime_with_default("ABC", date.today())        # Returns current datetime
value6 = DateTimeConverter.to_datetime_with_default("2021-11-09T17:24:50.750Z", date.today())   # Returns 2021-11-09 17:24:50.75

Not available

4) DoubleConverter

This class is used to convert arbitrary values into doubles using extended conversion rules. The rules and available methods are explained in the following tables and examples.

Conversion rules
String Converts to a double value.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_double Converts a value into a double or returns 0 when the conversion is not possible.
to_double_with_default Converts a value into a double or returns a default value when the conversion is not possible.
to_nullable_double Converts a value into a double or returns None when the conversion is not possible.
import { DoubleConverter } from "pip-services4-commons-node"

let value1 = DoubleConverter.toDouble("123.456");               // Returns 123.456
let value2 = DoubleConverter.toDouble("ABC");                   // Returns 0
let value3 = DoubleConverter.toDoubleWithDefault("123.456", 0); // Returns 123.456
let value4 = DoubleConverter.toDoubleWithDefault("ABC", 0);     // Returns 0
let value5 = DoubleConverter.toNullableDouble("123.456");       // Returns 123.456
let value6 = DoubleConverter.toNullableDouble("ABC");           // Returns null
let value7 = DoubleConverter.toNullableDouble(true);            // Returns 1

Not available
// Double converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.DoubleConverter.ToDouble("123.456")               // Returns 123.456
	value2 := convert.DoubleConverter.ToDouble("ABC")                   // Returns 0
	value3 := convert.DoubleConverter.ToDoubleWithDefault("123.456", 0) // Returns 123.456
	value4 := convert.DoubleConverter.ToDoubleWithDefault("ABC", 0)     // Returns 0
	value5, err := convert.DoubleConverter.ToNullableDouble("123.456")  // Returns 123.456
	value6, err := convert.DoubleConverter.ToNullableDouble("ABC")      // Returns nil
	value7, err := convert.DoubleConverter.ToNullableDouble(true)       // Returns 1
}
Not available
# Double converter

from pip_services4_commons.convert import DoubleConverter

value1 = DoubleConverter.to_double("123.456")                   # Returns 123.456
value2 = DoubleConverter.to_double("ABC")                       # Returns 0
value3 = DoubleConverter.to_double_with_default("123.456", 0)   # Returns 123.456
value4 = DoubleConverter.to_double_with_default("ABC", 0)       # Returns 0
value5 = DoubleConverter.to_nullable_double("123.456")       # Returns 123.456
value6 = DoubleConverter.to_nullable_double("ABC")           # Returns None
value7 = DoubleConverter.to_nullable_double(True)            # Returns 1
Not available

5) FloatConverter

This class can be used to convert arbitrary values into floats using extended conversion rules. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
String Converts to a float value.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_float Converts a value into a float or returns 0 when the conversion is not possible.
to_float_with_default Converts a value into a float or returns a default value when the conversion is not possible.
to_nullable_float Converts a value into a float or returns None when the conversion is not possible.
import { FloatConverter } from "pip-services4-commons-node"

let value1 = FloatConverter.toFloat("123.456");                 // Returns 123.456
let value2 = FloatConverter.toFloat("ABC");                     // Returns 0
let value3 = FloatConverter.toFloatWithDefault("123.456", 0);   // Returns 123.456
let value4 = FloatConverter.toFloatWithDefault("ABC", 0);       // Returns 0
let value5 = FloatConverter.toNullableFloat("123.456");         // Returns 123.456
let value6 = FloatConverter.toNullableFloat("ABC");             // Returns null
let value7 = FloatConverter.toNullableFloat(true);              // Returns 1

Not available
// Float converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.FloatConverter.ToFloat("123.456")               // Returns 123.456
	value2 := convert.FloatConverter.ToFloat("ABC")                   // Returns 0
	value3 := convert.FloatConverter.ToFloatWithDefault("123.456", 0) // Returns 123.456
	value4 := convert.FloatConverter.ToFloatWithDefault("ABC", 0)     // Returns 0
	value5, err := convert.FloatConverter.ToNullableFloat("123.456")  // Returns 123.456
	value6, err := convert.FloatConverter.ToNullableFloat("ABC")      // Returns nil
	value7, err := convert.FloatConverter.ToNullableFloat(true)       // Returns 1
}
Not available
# Float converter
from pip_services4_commons.convert import FloatConverter

value1 = FloatConverter.to_float("123.456")                 # Returns 123.456
value2 = FloatConverter.to_float("ABC")                     # Returns 0
value3 = FloatConverter.to_float_with_default("123.456", 0) # Returns 123.456
value4 = FloatConverter.to_float_with_default("ABC", 0)     # Returns 0
value5 = FloatConverter.to_nullable_float("123.456")        # Returns 123.456
value6 = FloatConverter.to_nullable_float("ABC")            # Returns None
value7 = FloatConverter.to_nullable_float(True)             # Returns 1

Not available

6) IntegerConverter

This class is used to convert arbitrary values into integers using extended conversion rules. Its methods and rules are explained in the following tables and examples.

Conversion rules
String Converts to float, then to integer.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_integer Converts a value into an integer or returns 0 when the conversion is not possible.
to_integer_with_default Converts a value into an integer or returns a default value when the conversion is not possible.
to_nullable_integer Converts a value into an integer or returns None when the conversion is not possible.
import { IntegerConverter } from "pip-services4-commons-node"

let value1 = IntegerConverter.toInteger("123.456");                 // Returns 123
let value2 = IntegerConverter.toInteger("ABC");                     // Returns 0
let value3 = IntegerConverter.toNullableInteger("123.456");         // Returns 123
let value4 = IntegerConverter.toNullableInteger("ABC");             // Returns null
let value5 = IntegerConverter.toNullableInteger(true);              // Returns 1
let value6 = IntegerConverter.toIntegerWithDefault("ABC", 123);     // Returns 123 
let value7 = IntegerConverter.toIntegerWithDefault("123.456", 123); // Returns 123 

Not available
// IntegerConverter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.IntegerConverter.ToInteger("123.456")                 // Returns 123
	value2 := convert.IntegerConverter.ToInteger("ABC")                     // Returns 0
	value3, err := convert.IntegerConverter.ToNullableInteger("123.456")    // Returns 123
	value4, err := convert.IntegerConverter.ToNullableInteger("ABC")        // Returns nil
	value5, err := convert.IntegerConverter.ToNullableInteger(true)         // Returns 1
	value6 := convert.IntegerConverter.ToIntegerWithDefault("ABC", 123)     // Returns 123
	value7 := convert.IntegerConverter.ToIntegerWithDefault("123.456", 123) // Returns 123
}
Not available
# IntegerConverter
from pip_services4_commons.convert import IntegerConverter

value1 = IntegerConverter.to_integer("123.456")                     # Returns 123
value2 = IntegerConverter.to_integer("ABC")                         # Returns 0
value3 = IntegerConverter.to_nullable_integer("123.456")            # Returns 123
value4 = IntegerConverter.to_nullable_integer("ABC")                # Returns None
value5 = IntegerConverter.to_nullable_integer(True)                 # Returns 1
value6 = IntegerConverter.to_integer_with_default("ABC", 123)       # Returns 123  
value7 = IntegerConverter.to_integer_with_default("123.456", 123)   # Returns 123  

Not available

7) LongConverter

This class is used to convert arbitrary values into longs using extended conversion rules. Its methods and rules are explained in the following tables and examples.

Conversion rules
String Converts to float, then to long.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_long Converts a value into a long or returns 0 when the conversion is not possible.
to_long_with_default Converts a value into a long or returns a default value when the conversion is not possible.
to_nullable_long Converts a value into a long or returns None when the conversion is not possible.
import { LongConverter } from "pip-services4-commons-node"

let value1 = LongConverter.toLong("123.456");               // Returns 123
let value2 = LongConverter.toLong("ABC");                   // Returns 0
let value3 = LongConverter.toNullableLong("123.456");       // Returns 123
let value4 = LongConverter.toNullableLong("ABC");           // Returns null
let value5 = LongConverter.toNullableLong(true);            // Returns 1
let value6 = LongConverter.toLongWithDefault("123.456", 0); // Returns 123
let value7 = LongConverter.toLongWithDefault("ABC", 0);     // Returns 0

Not available
// Long converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.LongConverter.ToLong("123.456")               // Returns 123
	value2 := convert.LongConverter.ToLong("ABC")                   // Returns 0
	value3, err := convert.LongConverter.ToNullableLong("123.456")  // Returns 123
	value4, err := convert.LongConverter.ToNullableLong("ABC")      // Returns nil
	value5, err := convert.LongConverter.ToNullableLong(true)       // Returns 1
	value6 := convert.LongConverter.ToLongWithDefault("123.456", 0) // Returns 123
	value7 := convert.LongConverter.ToLongWithDefault("ABC", 0)     // Returns 0
}
Not available
# Long converter

from pip_services4_commons.convert import LongConverter

value1 = LongConverter.to_long("123.456")                   # Returns 123
value2 = LongConverter.to_long("ABC")                       # Returns 0
value3 = LongConverter.to_nullable_long("123.456")          # Returns 123
value4 = LongConverter.to_nullable_long("ABC")              # Returns None
value5 = LongConverter.to_nullable_long(True)               # Returns 1
value6 = LongConverter.to_long_with_default("123.456", 0)   # Returns 123
value7 = LongConverter.to_long_with_default("ABC", 0)       # Returns 0
Not available

8) StringConverter

This class is used to convert arbitrary values into strings. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
Number Converts with '.' as decimal point.
DateTime Converts using the ISO format.
Boolean Converts "true" for true and "false" for false.
Array Converts as comma-separated list.
Other Converts using the to_string() method.
Method Description
to_string Converts a value into a string or returns "" when the value is None.
to_nullable_string Converts a value into a string or returns None when the value is None.
to_string_with_default Converts a value into a string or returns a default value when the value is None.
import { StringConverter } from "pip-services4-commons-node"

let value1 = StringConverter.toString(123.456);                 // Returns '123.456'
let value2 = StringConverter.toString(true);                    // Returns 'True'
let value3 = StringConverter.toString(new Date(2018, 10, 1));   // Returns '2018-10-01T00:00:00Z'
let value4 = StringConverter.toString([ "a", "b", "c" ]);       // Returns 'a,b,c'
let value5 = StringConverter.toString(null);                    // Returns ""
let value6 = StringConverter.toNullableString(null);            // Returns null
let value7 = StringConverter.toStringWithDefault(null, "my default");   // Returns 'my default' 

Not available
// String converter

import (
	"time"

	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.StringConverter.ToString(123.456)                                      // Returns '123.456'
	value2 := convert.StringConverter.ToString(true)                                         // Returns 'True'
	value3 := convert.StringConverter.ToString(time.Date(2018, 10, 1, 0, 0, 0, 0, time.UTC)) // Returns '2018-10-01T00:00:00Z'
	value4 := convert.StringConverter.ToString([]string{"a", "b", "c"})                      // Returns 'a,b,c'
	value5 := convert.StringConverter.ToString(nil)                                          // Returns ""
	value6, err := convert.StringConverter.ToNullableString(nil)                             // Returns nil
	value7 := convert.StringConverter.ToStringWithDefault(nil, "my default")                 // Returns 'my default'
}

Not available
# String converter

from pip_services4_commons.convert import StringConverter
import datetime

value1 = StringConverter.to_string(123.456)     # Returns '123.456'
value2 = StringConverter.to_string(True)        # Returns 'True'
value3 = StringConverter.to_string(datetime.datetime(2018,10,1))       # Returns '2018-10-01T00:00:00Z'
value4 = StringConverter.to_string(["a","b","c"])     # Returns 'a,b,c'
value5 = StringConverter.to_string(None)              # Returns ""
value6 = StringConverter.to_nullable_string(None)     # Returns None
value7 = StringConverter.to_string_with_default(None,"my default")     # Returns 'my default'  
Not available

9) JsonConverter

This class is used to convert arbitrary values (e.g. a JSON object) from and to JSON (JavaScript Object Notation) strings. Its methods are explained in the table and examples below.

Method Description
from_json Converts a JSON string into a value of the type specified by a TypeCode.
to_json Converts a value into a JSON string.
to_map Converts a JSON string into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a JSON string into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a JSON string into a map object or returns None when the conversion is not possible.
import { JsonConverter, TypeCode } from "pip-services4-commons-node"

let value1 = JsonConverter.toJson({ "key": 123 });                           // Returns '{"key": 123}'
let value2 = JsonConverter.fromJson(TypeCode.Map, "{\"key\":\"123\"}");      // Returns {'key': '123'}
let value3 = JsonConverter.toMap(value1);                                    // Returns {'key': 123}
let value4 = JsonConverter.toMapWithDefault(value1, { "my key": "my val" }); // Returns {'key': 123}
let value5 = JsonConverter.toMapWithDefault("", { "my key": "my val" });     // Returns { "my key": "my val" }
let value6 = JsonConverter.toNullableMap(value1);                            // Returns {'key': 123}
let value7 = JsonConverter.toNullableMap("{}");                              // Returns {}
  
Not available
// JSON converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1, _ := convert.JsonConverter.ToJson(map[string]int{"key": 123})                                // Returns '{"key": 123}'
	value2, _ := convert.JsonConverter.FromJson("{\"key\":\"123\"}")                                     // Returns {"key": 123}
	value3 := convert.JsonConverter.ToMap(value1)                                                        // Returns {"key": 123}
	value4 := convert.JsonConverter.ToMapWithDefault(value1, map[string]interface{}{"my key": "my val"}) // Returns {"key": 123}
	value5 := convert.JsonConverter.ToMapWithDefault("", map[string]interface{}{"my key": "my val"})     // Returns {}
	value6, _ := convert.JsonConverter.ToNullableMap(value1)                                             // Returns {'key': 123}
	value7, _ := convert.JsonConverter.ToNullableMap("{}")                                               // Returns {}
}
Not available
# JSON converter
from pip_services4_commons.convert import JsonConverter, TypeCode

value1 = JsonConverter.to_json({'key': 123})                                # Returns '{"key": 123}'
value2 = JsonConverter.from_json(TypeCode.Map, '{"key":"123"}')          # Returns {'key': '123'}
value3 = JsonConverter.to_map(value1)                                       # Returns {'key': 123}
value4 = JsonConverter.to_map_with_default(value1, {"my key": "my val"})    # Returns {'key': 123}
value5 = JsonConverter.to_map_with_default("", {"my key": "my val"})        # Returns {"my key": "my val"}
value6 = JsonConverter.to_nullable_map(value1)                              # Returns {'key': 123}
value7 = JsonConverter.to_nullable_map("")                                  # Returns None
Not available

10) MapConverter & RecursiveMapConverter

Both classes are used to convert arbitrary values into map objects using extended conversion rules. The difference between them is that RecursiveMapConverter uses recursion to convert all values stored in objects and arrays, and MapConverter doesn’t. The tables and examples below explain their methods and conversion rules.

Conversion rules
Objects Property names as keys, property values as values.
Arrays Element indexes as keys, elements as values.
MapConverter
Method Description
to_map Converts a value into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a value into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a value into a map object or returns None when the conversion is not possible.
import { MapConverter } from "pip-services4-commons-node"

let value1 = MapConverter.toNullableMap("ABC");                       // Returns null
let value2 = MapConverter.toNullableMap({ "key": 123 });              // Returns { key: 123 }
let value3 = MapConverter.toNullableMap([1, 2, 3]);                   // Returns { "0": 1, "1": 2, "2": 3 }
let value4 = MapConverter.toMap("ABC");                               // Returns {}
let value5 = MapConverter.toMapWithDefault("ABC", value2);            // Returns {'key': 123}
let value6 = MapConverter.toMapWithDefault({ "key": 12345 }, value2); // Returns {'key': 12345}

Not available
// Map converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1, _ := convert.MapConverter.ToNullableMap("ABC")                                        // Returns nil
	value2, _ := convert.MapConverter.ToNullableMap(map[string]interface{}{"key": 123})           // Returns { key: 123 }
	value3, _ := convert.MapConverter.ToNullableMap([]int{1, 2, 3})                               // Returns { "0": 1, "1": 2, "2": 3 }
	value4 := convert.MapConverter.ToMap("ABC")                                                   // Returns {}
	value5 := convert.MapConverter.ToMapWithDefault("ABC", value2)                                // Returns {'key': 123}
	value6 := convert.MapConverter.ToMapWithDefault(map[string]interface{}{"key": 12345}, value2) // Returns {'key': 12345}
}
Not available
# Map converter

from pip_services4_commons.convert import MapConverter

value1 = MapConverter.to_nullable_map("ABC")                        # Returns None
value2 = MapConverter.to_nullable_map({ 'key': 123 })               # Returns { key: 123 }
value3 = MapConverter.to_nullable_map([1,2,3])                      # Returns { "0": 1, "1": 2, "2": 3 }
value4 = MapConverter.to_map("ABC")                                 # Returns {}
value5 = MapConverter.to_map_with_default("ABC", value2)            # Returns {'key': 123}
value6 = MapConverter.to_map_with_default({ 'key': 12345 }, value2) # Returns {'key': 12345}

Not available
RecursiveMapConverter
Method Description
to_map Converts a value into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a value into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a value into a map object or returns None when the conversion is not possible.
import { RecursiveMapConverter } from "pip-services4-commons-node"

let value1 = RecursiveMapConverter.toMap({ "key": 123});                              // Returns {'key': 123}
let value2 = RecursiveMapConverter.toMapWithDefault(null, { "my key": "my val" });    // Returns { "my key": "my val" }
let value3 = RecursiveMapConverter.toNullableMap({ "key": 123 });                     // Returns {'key': 123}
let value4 = RecursiveMapConverter.toNullableMap([1,[2,3]]); // Returns {0: 1, 1: {0: 2, 1: 3}}

Not available
Please note that this is not implemented for this language yet.
Not available
# Recursive map
from pip_services4_commons.convert import RecursiveMapConverter

value1 = RecursiveMapConverter.to_map({ 'key': 123 })              # Returns {'key': 123}
value2 = RecursiveMapConverter.to_map_with_default(None, { "my key": "my val" })   # Returns { "my key": "my val" }
value3 = RecursiveMapConverter.to_nullable_map({ 'key': 123 })     # Returns {'key': 123}
value4 = RecursiveMapConverter.to_nullable_map([1,[2,3]])          # Returns {0: 1, 1: {0: 2, 1: 3}}
Not available

11) TypeConverter

This class is used to convert arbitrary values into objects specified by a TypeCode and to get the TypeCode of an object. Its methods are explained in the table and examples below. Note: Code types are defined in the TypeCode class available in the same package.

Method Description
to_nullable_type Converts a value into an object type specified by a TypeCode or returns None when the conversion is not possible.
to_string Converts a TypeCode into its string name.
to_type Converts a value into an object type specified by a TypeCode
to_type_code Gets the TypeCode for a specific value.
to_type_with_default Converts a value into an object type specified by TypeCode or returns a default value when the conversion is not possible.
import { TypeConverter, TypeCode } from "pip-services4-commons-node"

let value1 = TypeConverter.toType(TypeCode.String, 123);                  // Returns '123'
let value2 = TypeConverter.toNullableType(TypeCode.String, 123);          // Returns '123'
let value3 = TypeConverter.toTypeWithDefault(TypeCode.Integer, "ABC", 1); // 1
let value4 = TypeConverter.toTypeCode("Hello world");                     // Returns TypeCode.String
let value5 = TypeConverter.toString(TypeCode.String);                     // Returns 'string'

Not available
// Type converter

import (
	convert "github.com/pip-services4/pip-services4-go/pip-services4-commons-go/convert"
)

func main() {
	value1 := convert.TypeConverter.ToType(convert.String, 123)                  // Returns '123'
	value2, _ := convert.TypeConverter.ToNullableType(convert.String, 123)       // Returns '123'
	value3 := convert.TypeConverter.ToTypeWithDefault(convert.Integer, "ABC", 1) // Returns 1
	value4 := convert.TypeConverter.ToTypeCode("Hello world")                    // Returns TypeCode.String
	value5 := convert.TypeConverter.ToString(convert.String)                     // Returns 'string'
}
Not available
# Type converter

from pip_services4_commons.convert import TypeCode, TypeConverter

value1 = TypeConverter.to_type(TypeCode.String, 123)             # Returns '123'
value2 = TypeConverter.to_nullable_type(TypeCode.String, 123)    # Returns '123'
value3 = TypeConverter.to_type_with_default(TypeCode.Integer, 'ABC', 1)    # 1
value4 = TypeConverter.to_type_code("Hello world")               # Returns TypeCode.String
value5 = TypeConverter.to_string(TypeCode.String)                # Returns 'string'
Not available

Wrapping up

In this tutorial, we have seen several components that provide methods with conversion mechanisms for arrays, Booleans, dates, doubles, floats, integers, longs, strings, JSON objects, maps and types defined by a type code.