In the paper we propose a direct method for recovering the Sturm–Liouville potential from the Weyl–Titchmarsh m-function given on a countable set of points. We show that using the Fourier–Legendre series expansion of the transmutation operator integral kernel the problem reduces to an infinite linear system of equations, which is uniquely solvable if so is the original problem. The solution of this linear system allows one to reconstruct the characteristic determinant and hence to obtain the eigenvalues as its zeros and to compute the corresponding norming constants. As a result, the original inverse problem is transformed to an inverse problem with a given spectral density function, for which the direct method of solution from Kravchenko and Torba (2021 Inverse Problems 37 015015) is applied. The proposed method leads to an efficient numerical algorithm for solving a variety of inverse problems. In particular, the problems in which two spectra or some parts of three or more spectra are given, the problems in which the eigenvalues depend on a variable boundary parameter (including spectral parameter dependent boundary conditions), problems with a partially known potential and partial inverse problems on quantum graphs.