Home > Software engineering >  Convert List of Tuples to JSON in python
Convert List of Tuples to JSON in python

Time:11-16

I have a list of tuple with 50 records which look something like below:

tuple_list = [(1,2,3),(2,3,4),(5,3,2),(4,3,1),(8,6,5)]

I want to be able to convert it to a JSON format which looks something like this: json = [{ link: 1, title: 2, desc:3},{ link: 2, title: 3, desc: 4},{ link: 5, title: 3, desc:2},{ link: 4, title: 3, desc: 1},{ link: 8, title: 6, desc:5}]

I tried converting it to the dictionary and then to JSON, directly dumping it to JSON but I am getting errors. Can someone point me to how to do it?

Methods I tried: 1.

import json
lst = [("name", "value"), ("name2", "value2")]
rs = json.dumps(dict(lst))
print(rs) 
  1. Converted it to Dataframe and tried to put to JSON

    df.to_json('temp.json', orient='records', lines=True)

CodePudding user response:

Not sure if you framed the question correctly or used the right phrases, but if you are trying to convert the tuple to a dictionary, there are multiple ways. A one liner approach would be

my_dict = [dict(zip(("link", "title", "desc"), x)) for x in tuple_list]
print(my_dict)

which gives

[{'link': 1, 'title': 2, 'desc': 3}, {'link': 2, 'title': 3, 'desc': 4}, {'link': 5, 'title': 3, 'desc': 2}, {'link': 4, 'title': 3, 'desc': 1}, {'link': 8, 'title': 6, 'desc': 5}]

CodePudding user response:

You can try dict comprehension:

{k:v for (k,v) in lst}

Output

{'name': 'value', 'name2': 'value2'}

Can then convert to json, using json.dumps

  • Related