Exemple #1
0
    def encode(self, o):
        """
        Encode a given python object

        :type  o: :class:`object`
        :param o: Python object
        :rtype: :class:`str`
        :return: JSON string in canonicalized form
        """
        if isinstance(o, dict):
            # Remove non-significant whitespace characters
            # Keys are sorted lexicographically using UCS code
            # point values
            sorted_keys = sorted(o.keys())
            sorted_items = [
                '%s:%s' % (self.encode(key), self.encode(o[key]))
                for key in sorted_keys
            ]
            string = ','.join(sorted_items)
            return '{%s}' % string
        elif isinstance(o, list):
            # Arrays must preserve the initial ordering
            # Remove non-significant whitespace characters
            string = ','.join([self.encode(item) for item in o])
            return '[%s]' % string
        elif isinstance(o, decimal.Decimal):
            return canonicalize_double(o)
        else:
            return json.JSONEncoder.encode(self, o)
Exemple #2
0
    def visit_double_value(value):
        """
        Visit a DoubleValue object

        :type  value: :class:`vmware.vapi.data.value.DoubleValue`
        :param value: Double value object
        :rtype: :class:`str`
        :return: JSON string
        """
        return canonicalize_double(value.value)
 def test_double(self):
     for input_val, expected in [
         ('3.33', '3.33E0'),
         ('3.0033', '3.0033E0'),
         ('3333.333', '3.333333E3'),
         ('3333.333000', '3.333333E3'),
         ('3333.0003000', '3.3330003E3'),
         ('-3333.333000', '-3.333333E3'),
         ('0.3333', '3.333E-1'),
         ('0.00333', '3.33E-3'),
         ('-0.00333', '-3.33E-3'),
         ('0', '0.0E0'),
         ('-0', '-0.0E0'),
         ('-0.0E-0', '-0.0E0'),
         ('+0', '0.0E0'),
         ('+0.00', '0.0E0'),
         ('-12.34E4', '-1.234E5'),
         ('1111111.1111100021e-30', '1.1111111111100021E-24'),
         ('0.000234E-10', '2.34E-14'),
         ('0.000234E+10', '2.34E6'),
     ]:
         actual_output = canonicalize_double(Decimal(input_val))
         self.assertEqual(actual_output, expected)