wasi-master / sponsorblock.py

An unofficial wrapper and a cli for the Sponsorblock API
https://sponsorblockpy.readthedocs.io/en/latest/
MIT License
23 stars 2 forks source link

Convert segment to JSON string #1

Closed JVT038 closed 3 years ago

JVT038 commented 3 years ago

Hi, So I want to use get_skip_segments to fetch segments from a YouTube video in JSON format, so JavaScript can use it. However, the results are apparently Segment objects inside a list wrapper. Is there a way for me to convert the segment objects into a JSON string, so I can use it for JavaScript? Because I now get this error: TypeError: Object of type Segment is not JSON serializable

wasi-master commented 3 years ago

You can use the Segment.data attribute to get the raw data then format it as json using json.dumps

import json
import sponsorblock as sb

client = sb.Client()

segments = client.get_skip_segments("https://www.youtube.com/watch?v=kJQP7kiw5Fk")
segment = segments[0]  # Getting the first segment

json_data = json.dumps(segment.data)
print(json_data)

And you can use Segment.from_dict to generate the segment object again from the JSON data

JVT038 commented 3 years ago

Thanks!

wasi-master commented 3 years ago

@JVT038 Also I may ask, why aren't you using something specifically made for javascript like https://www.npmjs.com/package/sponsorblock-api?

JVT038 commented 3 years ago

Because I'm building a web application with Python + Flask as backend and JavaScript / CSS / HTML as frontend. Here's my repo Basically, my frontend will send an Ajax call to my backend (python) and my backend will fetch the data with your library, and send it back to JavaScript, and JavaScript will show it to the end-user.

wasi-master commented 3 years ago

@JVT038 Oh nice, good job!