Last active
July 25, 2024 16:57
-
-
Save Amir-P/d7017ce65da1bd40f4372dfbd2b68ec2 to your computer and use it in GitHub Desktop.
Convert JSON exported contacts from Telegram to vCard (.vcf)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import json | |
| input_file = sys.argv[1] | |
| output_file = sys.argv[2] | |
| output_file = open(output_file, 'w') | |
| def to_vcf_string(first_name, last_name, phone): | |
| vcf_lines = [] | |
| vcf_lines.append('BEGIN:VCARD') | |
| vcf_lines.append('VERSION:4.0') | |
| vcf_lines.append('N:%s' % (last_name + ';' + first_name)) | |
| vcf_lines.append('FN:%s' % (first_name + ('' if len(last_name) == 0 else ' ') + last_name)) | |
| vcf_lines.append('TEL:%s' % phone) | |
| vcf_lines.append('END:VCARD') | |
| vcf_string = '\n'.join(vcf_lines) + '\n' | |
| return vcf_string | |
| with open(input_file) as json_file: | |
| data = json.load(json_file) | |
| contacts_list = data['contacts']['list'] | |
| for contact in contacts_list: | |
| first_name = contact['first_name'] | |
| last_name = contact['last_name'] | |
| if len(first_name) == 0 and len(last_name) == 0: | |
| continue | |
| phone = contact['phone_number'] | |
| output_file.write(to_vcf_string(first_name, last_name, phone).encode('utf-8')) | |
| output_file.close() |
this version of edited code works for me, reads utf-8 characters from JSON file and writes bytes on the output file :
import sys
import json
input_file = sys.argv[1]
output_file = sys.argv[2]
output_file = open(output_file, 'wb')
def to_vcf_string(first_name, last_name, phone):
vcf_lines = [
'BEGIN:VCARD',
'VERSION:4.0',
f'N:{last_name};{first_name}',
f'FN:{first_name}{" " if last_name else ""}{last_name}',
f'TEL:{phone}',
'END:VCARD'
]
vcf_string = '\n'.join(vcf_lines) + '\n'
return vcf_string
with open(input_file, 'r', encoding='utf-8') as json_file:
data = json.load(json_file)
contacts_list = data['contacts']['list']
for contact in contacts_list:
first_name = contact['first_name']
last_name = contact['last_name']
if len(first_name) == 0 and len(last_name) == 0:
continue
phone = contact['phone_number']
output_file.write(to_vcf_string(first_name, last_name, phone).encode('utf-8'))
output_file.close()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. Just run the script passing json file path and desired output path as input like this:
python converter.py json_file_path output_file_path. @MrWesturn