How to generate a vobject from a string

176 views Asked by At

I have a Vcard string and I want to transform it to a Vobject : I did the following and I got the mentioned error , my question is what is this error and how can I transform a string to a vcard object?

    my_str = "BEGIN:VCARD
              VERSION:3.0
              N;CHARSET=UTF-8:ContactName;;;;
              TEL:0000000000
              END:VCARD"
   vcard = vobject.readOne(my_str)

stack trace:

error: Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/vobject/base.py", line 1156, in readOne
    allowQP))
  File "/usr/local/lib/python2.7/dist-packages/vobject/base.py", line 1142, in readComponents
    (stack.topName())), n)
vobject.base.ParseError: At line 1: Component VCARD was never closed
1

There are 1 answers

0
David Arnold On

What is this error?

As posted, the supplied code will raise a SyntaxError: as @Frodon's comment says, you would need to use """ (or ''') to have the string span multiple lines like that.

For example, this code:

s = "abc
def"

print(s)

Causes the interpreter to report:

> python test.py 
File "test_files/test.py", line 1
s = "abc
       ^
SyntaxError: EOL while scanning string literal

The reported error from vobject means that the string you're actually trying to parse has no "END:VCARD" line.

For example

>>> import vobject
>>> s = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:abcdef\r\nN:Smith;John;Quinlan;Dr;Jr\r\nFN:Dr John Quinlan Smith Jr\r\nEND:VCARD"
>>> vcard = vobject.readOne(s)
>>> vcard.prettyPrint()
 VCARD
    VERSION: 3.0
    UID: abcdef
    N: Dr John Quinlan Smith Jr
    FN: Dr John Quinlan Smith Jr
>>>

but

>>> import vobject
>>> # Note: no END:VCARD in the card data!
>>> s = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:abcdef\r\nN:Smith;John;Quinlan;Dr;Jr\r\nFN:Dr John Quinlan Smith Jr\r\n"
>>> vcard = vobject.readOne(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/xxx/vobject/vobject/base.py", line 1155, in readOne
    return next(readComponents(stream, validate, transform, ignoreUnreadable,
  File "/xxx/vobject/vobject/base.py", line 1141, in readComponents
    raise ParseError("Component {0!s} was never closed".format(
vobject.base.ParseError: At line 9: Component VCARD was never closed
>>> 

How can I transform a string to a vcard object?

To your second question, for parsing a vCard, you're doing the right thing: use vobject.readOne() or vobject.readComponents(). If your input data doesn't have the END:VCARD line truncated, it should parse correctly, returning you a vCard object.