<p>I want to list my k8s jobs with a label selector by <a href="https://github.com/kubernetes/client-go" rel="nofollow noreferrer">client-go</a> like this command:</p>
<pre><code>$ kubectl get jobs -l 'hello-world in (London, China, NewYork)'
</code></pre>
<p>I looked through the source code of client-go, then I wrote some code like this:</p>
<pre class="lang-golang prettyprint-override"><code>func listJobs(cli *kubernetes.Clientset) (*batchv1.JobList, error) {
    label := metav1.LabelSelector{
        MatchExpressions: []metav1.LabelSelectorRequirement{
            {
                Key:      &quot;hello-world&quot;,
                Operator: metav1.LabelSelectorOpIn,
                Values: []string{
                    &quot;London&quot;,
                    &quot;China&quot;,
                    &quot;NewYork&quot;,
                },
            },
        },
    }

    fmt.Println(label.String())

    return cli.BatchV1().Jobs(&quot;default&quot;).List(context.TODO(), metav1.ListOptions{
        LabelSelector: label.String(),
    })
}
</code></pre>
<p>and then I got the error:</p>
<pre><code>&amp;LabelSelector{MatchLabels:map[string]string{},MatchExpressions:[]LabelSelectorRequirement{LabelSelectorRequirement{Key:hello-world,Operator:In,Values:[London China NewYork],},},}
2021/01/28 17:58:07 unable to parse requirement: invalid label key &quot;&amp;LabelSelector{MatchLabels:map[string]string{}&quot;: name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')
</code></pre>
<p>Where did I go wrong? How do I list my jobs with a label selector which is a complex expression?</p>

Reed Chan
<p>Using the Kubernetes <code>client-go</code> library, you can simply write label selectors the same way you would with <code>kubectl</code>.</p>
<p>Writing <code>hello-world in (London, China, NewYork)</code> should work just fine.</p>
<pre class="lang-golang prettyprint-override"><code>func listJobs(cli *kubernetes.Clientset) (*batchv1.JobList, error) {
    return cli.BatchV1().Jobs(&quot;default&quot;).List(context.TODO(), metav1.ListOptions{
        LabelSelector: &quot;hello-world in (London, China, NewYork)&quot;,
    })
}
</code></pre>
<p>If what you want is to dynamically generate <code>hello-world in (London, China, NewYork)</code> from a programmatic object however, that is another question, which is already answered on StackOverflow <a href="https://stackoverflow.com/questions/56231176/kubernetes-client-go-convert-labelselector-to-label-string">here</a>.</p>
