TypeError: cannot serialize x.x (type float) (Elementtree)











up vote
-2
down vote

favorite












I'm trying to print an ElementTree using python 3.6. Here is a reproducible example of my code:



from xml.etree import ElementTree as ET
root = ET.Element('gpx')
el = ET.SubElement(root, 'test')
el.text = 0.3
print(ET.dump(root))


Error message is:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1177, in dump
elem.write(sys.stdout, encoding="unicode")
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
write(_escape_cdata(text))
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1074, in _escape_cdata
_raise_serialization_error(text)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1057, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 0.3 (type float)


Serializing a float type must be something very commonly done, buut I can't find a satisfactory answer on how to do this- what is the standard method?



Research:



I can find one question on stack overflow about this, but it suggests cooecing the float to a string,I need the output to be numeric.



There's an old discussion regarding this on the google forums, but this is 10 years old, and involves using the simplejson library- an extra library seems like overkill for this, especially when there is potentially a more modern solution










share|improve this question






















  • @downvoters care to explain?
    – User632716
    Nov 19 at 13:05






  • 1




    The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
    – MisterMiyagi
    Nov 19 at 13:23






  • 1




    "I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
    – Goyo
    Nov 19 at 13:29















up vote
-2
down vote

favorite












I'm trying to print an ElementTree using python 3.6. Here is a reproducible example of my code:



from xml.etree import ElementTree as ET
root = ET.Element('gpx')
el = ET.SubElement(root, 'test')
el.text = 0.3
print(ET.dump(root))


Error message is:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1177, in dump
elem.write(sys.stdout, encoding="unicode")
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
write(_escape_cdata(text))
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1074, in _escape_cdata
_raise_serialization_error(text)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1057, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 0.3 (type float)


Serializing a float type must be something very commonly done, buut I can't find a satisfactory answer on how to do this- what is the standard method?



Research:



I can find one question on stack overflow about this, but it suggests cooecing the float to a string,I need the output to be numeric.



There's an old discussion regarding this on the google forums, but this is 10 years old, and involves using the simplejson library- an extra library seems like overkill for this, especially when there is potentially a more modern solution










share|improve this question






















  • @downvoters care to explain?
    – User632716
    Nov 19 at 13:05






  • 1




    The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
    – MisterMiyagi
    Nov 19 at 13:23






  • 1




    "I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
    – Goyo
    Nov 19 at 13:29













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











I'm trying to print an ElementTree using python 3.6. Here is a reproducible example of my code:



from xml.etree import ElementTree as ET
root = ET.Element('gpx')
el = ET.SubElement(root, 'test')
el.text = 0.3
print(ET.dump(root))


Error message is:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1177, in dump
elem.write(sys.stdout, encoding="unicode")
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
write(_escape_cdata(text))
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1074, in _escape_cdata
_raise_serialization_error(text)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1057, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 0.3 (type float)


Serializing a float type must be something very commonly done, buut I can't find a satisfactory answer on how to do this- what is the standard method?



Research:



I can find one question on stack overflow about this, but it suggests cooecing the float to a string,I need the output to be numeric.



There's an old discussion regarding this on the google forums, but this is 10 years old, and involves using the simplejson library- an extra library seems like overkill for this, especially when there is potentially a more modern solution










share|improve this question













I'm trying to print an ElementTree using python 3.6. Here is a reproducible example of my code:



from xml.etree import ElementTree as ET
root = ET.Element('gpx')
el = ET.SubElement(root, 'test')
el.text = 0.3
print(ET.dump(root))


Error message is:



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1177, in dump
elem.write(sys.stdout, encoding="unicode")
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
write(_escape_cdata(text))
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1074, in _escape_cdata
_raise_serialization_error(text)
File "/usr/local/lib/python3.6/xml/etree/ElementTree.py", line 1057, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 0.3 (type float)


Serializing a float type must be something very commonly done, buut I can't find a satisfactory answer on how to do this- what is the standard method?



Research:



I can find one question on stack overflow about this, but it suggests cooecing the float to a string,I need the output to be numeric.



There's an old discussion regarding this on the google forums, but this is 10 years old, and involves using the simplejson library- an extra library seems like overkill for this, especially when there is potentially a more modern solution







python python-3.x elementtree






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 at 11:49









User632716

2,41011234




2,41011234












  • @downvoters care to explain?
    – User632716
    Nov 19 at 13:05






  • 1




    The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
    – MisterMiyagi
    Nov 19 at 13:23






  • 1




    "I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
    – Goyo
    Nov 19 at 13:29


















  • @downvoters care to explain?
    – User632716
    Nov 19 at 13:05






  • 1




    The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
    – MisterMiyagi
    Nov 19 at 13:23






  • 1




    "I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
    – Goyo
    Nov 19 at 13:29
















@downvoters care to explain?
– User632716
Nov 19 at 13:05




@downvoters care to explain?
– User632716
Nov 19 at 13:05




1




1




The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
– MisterMiyagi
Nov 19 at 13:23




The issue is rather self-explanatory: text must be text. You already did find the standard method, namely store-as-string, yet you reject this for a nonsensical reason: it is not meaningful to store numeric output in text format, other than using the store-as-string approach or similar. Without further information, it is impossible to know why you reject this and thus also which alternatives are suitable.
– MisterMiyagi
Nov 19 at 13:23




1




1




"I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
– Goyo
Nov 19 at 13:29




"I need the output to be numeric" What output? The output of ET.dump is going to be a string (or bytes) anyway.
– Goyo
Nov 19 at 13:29












2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted










Interesting. I see that it is not going to work with a float because the _escape_cdata function uses the in operator (if "&" in text).



Also, the docstring for the text attribute indicates that it is either a string or None. The documentation, however, says that the "values are usually strings but may be any application-specific object", which I find misleading.



If you need to get other types when parsing an XML document, I recommend you use lxml.objectify






share|improve this answer






























    up vote
    0
    down vote













    You must set text to a text value:



    >>> from xml.etree import ElementTree as ET
    ... root = ET.Element('gpx')
    ... el = ET.SubElement(root, 'test')
    ... el.text = '0.3'
    ... print(ET.dump(root))
    <gpx><test>0.3</test></gpx>


    Simply put, text can only store text - there is no way to signal that a text node stores another type. Any other types must be serialised for storing, and de-serialised for usage.



    Note that the float, being a primitive type, is still stored verbatim as the literal '0.3'. You can convert it back easily:



    >>> print(el.text)
    '0.3'
    >>> print(float(el.text))
    0.3


    Keep in mind that XML is a text format - it can only store text. If you want other data types, you must define how the text is to be interpreted as the target type. For example, you can use an XML Schema Definition (XSD) to define a field as xs:integer. You can also embed a type marker in your texts - e.g. storing f0.3 or i7331 to mark floats and integers. However, all of these need a parser that is aware of such conventions, even for XSD.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53374038%2ftypeerror-cannot-serialize-x-x-type-float-elementtree%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote



      accepted










      Interesting. I see that it is not going to work with a float because the _escape_cdata function uses the in operator (if "&" in text).



      Also, the docstring for the text attribute indicates that it is either a string or None. The documentation, however, says that the "values are usually strings but may be any application-specific object", which I find misleading.



      If you need to get other types when parsing an XML document, I recommend you use lxml.objectify






      share|improve this answer



























        up vote
        2
        down vote



        accepted










        Interesting. I see that it is not going to work with a float because the _escape_cdata function uses the in operator (if "&" in text).



        Also, the docstring for the text attribute indicates that it is either a string or None. The documentation, however, says that the "values are usually strings but may be any application-specific object", which I find misleading.



        If you need to get other types when parsing an XML document, I recommend you use lxml.objectify






        share|improve this answer

























          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          Interesting. I see that it is not going to work with a float because the _escape_cdata function uses the in operator (if "&" in text).



          Also, the docstring for the text attribute indicates that it is either a string or None. The documentation, however, says that the "values are usually strings but may be any application-specific object", which I find misleading.



          If you need to get other types when parsing an XML document, I recommend you use lxml.objectify






          share|improve this answer














          Interesting. I see that it is not going to work with a float because the _escape_cdata function uses the in operator (if "&" in text).



          Also, the docstring for the text attribute indicates that it is either a string or None. The documentation, however, says that the "values are usually strings but may be any application-specific object", which I find misleading.



          If you need to get other types when parsing an XML document, I recommend you use lxml.objectify







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 at 12:52

























          answered Nov 19 at 12:42









          Carlos Mermingas

          2,21021029




          2,21021029
























              up vote
              0
              down vote













              You must set text to a text value:



              >>> from xml.etree import ElementTree as ET
              ... root = ET.Element('gpx')
              ... el = ET.SubElement(root, 'test')
              ... el.text = '0.3'
              ... print(ET.dump(root))
              <gpx><test>0.3</test></gpx>


              Simply put, text can only store text - there is no way to signal that a text node stores another type. Any other types must be serialised for storing, and de-serialised for usage.



              Note that the float, being a primitive type, is still stored verbatim as the literal '0.3'. You can convert it back easily:



              >>> print(el.text)
              '0.3'
              >>> print(float(el.text))
              0.3


              Keep in mind that XML is a text format - it can only store text. If you want other data types, you must define how the text is to be interpreted as the target type. For example, you can use an XML Schema Definition (XSD) to define a field as xs:integer. You can also embed a type marker in your texts - e.g. storing f0.3 or i7331 to mark floats and integers. However, all of these need a parser that is aware of such conventions, even for XSD.






              share|improve this answer



























                up vote
                0
                down vote













                You must set text to a text value:



                >>> from xml.etree import ElementTree as ET
                ... root = ET.Element('gpx')
                ... el = ET.SubElement(root, 'test')
                ... el.text = '0.3'
                ... print(ET.dump(root))
                <gpx><test>0.3</test></gpx>


                Simply put, text can only store text - there is no way to signal that a text node stores another type. Any other types must be serialised for storing, and de-serialised for usage.



                Note that the float, being a primitive type, is still stored verbatim as the literal '0.3'. You can convert it back easily:



                >>> print(el.text)
                '0.3'
                >>> print(float(el.text))
                0.3


                Keep in mind that XML is a text format - it can only store text. If you want other data types, you must define how the text is to be interpreted as the target type. For example, you can use an XML Schema Definition (XSD) to define a field as xs:integer. You can also embed a type marker in your texts - e.g. storing f0.3 or i7331 to mark floats and integers. However, all of these need a parser that is aware of such conventions, even for XSD.






                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You must set text to a text value:



                  >>> from xml.etree import ElementTree as ET
                  ... root = ET.Element('gpx')
                  ... el = ET.SubElement(root, 'test')
                  ... el.text = '0.3'
                  ... print(ET.dump(root))
                  <gpx><test>0.3</test></gpx>


                  Simply put, text can only store text - there is no way to signal that a text node stores another type. Any other types must be serialised for storing, and de-serialised for usage.



                  Note that the float, being a primitive type, is still stored verbatim as the literal '0.3'. You can convert it back easily:



                  >>> print(el.text)
                  '0.3'
                  >>> print(float(el.text))
                  0.3


                  Keep in mind that XML is a text format - it can only store text. If you want other data types, you must define how the text is to be interpreted as the target type. For example, you can use an XML Schema Definition (XSD) to define a field as xs:integer. You can also embed a type marker in your texts - e.g. storing f0.3 or i7331 to mark floats and integers. However, all of these need a parser that is aware of such conventions, even for XSD.






                  share|improve this answer














                  You must set text to a text value:



                  >>> from xml.etree import ElementTree as ET
                  ... root = ET.Element('gpx')
                  ... el = ET.SubElement(root, 'test')
                  ... el.text = '0.3'
                  ... print(ET.dump(root))
                  <gpx><test>0.3</test></gpx>


                  Simply put, text can only store text - there is no way to signal that a text node stores another type. Any other types must be serialised for storing, and de-serialised for usage.



                  Note that the float, being a primitive type, is still stored verbatim as the literal '0.3'. You can convert it back easily:



                  >>> print(el.text)
                  '0.3'
                  >>> print(float(el.text))
                  0.3


                  Keep in mind that XML is a text format - it can only store text. If you want other data types, you must define how the text is to be interpreted as the target type. For example, you can use an XML Schema Definition (XSD) to define a field as xs:integer. You can also embed a type marker in your texts - e.g. storing f0.3 or i7331 to mark floats and integers. However, all of these need a parser that is aware of such conventions, even for XSD.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 19 at 13:42

























                  answered Nov 19 at 12:50









                  MisterMiyagi

                  7,2252040




                  7,2252040






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53374038%2ftypeerror-cannot-serialize-x-x-type-float-elementtree%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                      Alcedinidae

                      Origin of the phrase “under your belt”?