Given $x>0$ a simple strategy is to choose, in the $n$-th step, the maximum $a_n$ such that
$$ x-\sum_{j=1}^{n}\frac{a_j}{j^2}$$
is non-negative. Since the series
$$\sum_{j=1}^{+\infty}\frac{j-1}{j^2}$$
is diverging, but the general term is infinitesimal, we can get arbitrarily close (i.e. converge towards) any positive real number. For example, let us represent $\frac{1}{3}$ this way. The first square bigger than $3$ is $4$, hence we just need to represent $\frac{1}{3}-\frac{1}{4}=\frac{1}{12}$ as $\sum_{n\geq 3}\frac{a_n}{n^2}$. We have to choose $a_3=0$, since $\frac{1}{9}>\frac{1}{12}$, then by taking $a_4=1$ and just have to represent $\frac{1}{12}-\frac{1}{16}=\frac{1}{48}$ as $\sum_{n\geq 5}\frac{a_n}{n^2}$. This leads to your second formula (a representation with an infinite series).
However, as soon as we have to represent a number of the form $\frac{1}{mk^2}$ with $\gcd(m,k)=1$, we just have to subtract $\frac{m}{(mk)^2}$. So, in order to represent $x=\frac{p}{q}$ as a finite sum, we can first focus on decreasing the numerator. This is related to a famous problem.
Let us exhibit an algorithm for finding a representation of a rational number.
By subtracting a few terms, we can assume to have to represent $\frac{p}{q}$ with $1<p<q$. The question is now: given $N$, it is possible to find a few terms of the form $\frac{m}{n^2}$, with $n>N,m<n$, such that $\frac{p}{q}-\sum\frac{m}{n^2}$ is positive and its numerator is one? The answer is affirmative.
It is sufficient to take our $n$'s in the set of integers whose prime divisors belong to the prime divisors of $q$ and adjust, step by step, the base-$p_i$ representation of $\frac{p}{q}-\sum\frac{m}{n^2}$ for any prime divisor $p_i$ of $q$.
Another possible approach is just to show that the rational numbers that can be represented as sums of $\frac{m_i}{n_i^2}$ with $1\leq m_i<n_i$ are an additive semigroup of $\mathbb{Q}^+$. That is pretty straightforward to prove: we just have to sum two representations, then "fixing" terms like $\frac{l_i}{n_i^2}$ where $n_i\leq l_i\leq 2n_i-2$ by writing them as $\frac{n_i-1}{n_i^2}+\frac{4(l_i-n_i+1)}{(2n_i)^2}$. So we sum two representations and fix it by adjusting its terms, starting by the one with the lowest denominator. Since we can obviously represent $\frac{1}{n^2}$, we can represent $\frac{1}{n}$, hence any rational number.