Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of JToken to a list of one of the values

Tags:

c#

linq

json.net

I have a list of json JTokens:

List<JToken> subjectresults = jObj[jp]["subjects"].Children().ToList();

Note that my jp is var jp = jObj.Properties().First().Name; because the name is dynamic.

Each of the tokens contains two further items, a url and a name.
I want to get a list of strings that contains just the name value, from this list of jtokens.

So that:

[0]: {{
  "url": "https://openlibrary.org/subjects/science",
  "name": "Science"
}}

    [1]: {{
  "url": "https://openlibrary.org/subjects/in_library",
  "name": "In library"
}}

Becomes:

{"Science", "In library"}

I can't seem to figure out the syntax. Or alternatively how do I skip the tokens and go right to my list. I didn't strongly type this, because the parent property has the dynamic name, and I only needed a couple of the fields.

like image 981
Martian99 Avatar asked Oct 28 '25 05:10

Martian99


1 Answers

I suppose that subjects-property is Array:

var jObj = JObject.Parse(json);

var jp = jObj.Properties().First().Name;
var subjectresults = jObj[jp]["subjects"]
    .Children()
    .Select(v => v["name"].Value<string>())
    .ToArray();

/*
subjectresults
{string[2]}
[0] [string]:"Science"
[1] [string]:"In library"
*/

The source json:

var json = @"{
        ""name"": {
            ""subjects"": [
                {
                    ""url"": ""https://openlibrary.org/subjects/science"",
                    ""name"": ""Science""
                },
                {
                    ""url"": ""https://openlibrary.org/subjects/in_library"",
                    ""name"": ""In library""
                }
            ]
        }                
    }"; 
like image 127
vladimir Avatar answered Oct 29 '25 18:10

vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!