The ability to encode and simplify all information about the shape and distribution of data has turned Topological Data Analysis (TDA) into one of the most relevant fields in state-of-the-art data analysis. Among all the tools of TDA, persistent homology has proven to be one of the most relevant techniques, and has been applied in numerous fields of study, such as biomedicine, chemistry, atomic physics, or image classification. In this work, we study what persistent homology can offer in the analysis of solar magnetograms, with the purpose of providing a new tool that will serve as foundation for further studies of magnetic structures on the solar surface. We propose an approach based on the use of persistence diagrams belonging to various filtrations in order to be able to capture the whole magnetic scene involving a mixture of positive and negative polarities. We have applied the analysis to quiet sun and active regions observations, taken with both Hinode/SOT and SDO/HMI, respectively. Persistent diagrams have proven to be able to encode the spatial structure complexity of the magnetic flux of active regions by identifying the isolated and connected (interacting) structures. Holes or pores are also displayed in persistent diagrams, allowing as well for the identification of interacting structures of opposite polarities in the form of ring-like structures. The overall temporal evolution of active regions, as well as small scale events in quiet sun such as magnetic flux cancellation and emergence are also displayed in persistent diagrams and can be studied by observing the evolution of the diagrams and tracking the relevant features.