Search code examples
c#jsonjson.netdiscord.net

Having error upon trying to parse a JSON array into JSON object


I am trying to parse a JSON array by using this code:

public async Task QuoteAsync()
{
    await this.Context.Channel.TriggerTypingAsync();
    var client = new HttpClient();
    var result = await client.GetStringAsync("https://zenquotes.io/api/random");
    JArray qarray = JArray.Parse(result);
    JObject quote = JObject.Parse(qarray[0]["q"].ToString());
    JObject author = JObject.Parse(qarray[0]["a"].ToString());
    await this.ReplyAsync($"{quote} - {author}");
}

The response I receive upon sending a request to zenquotes api is

[
  {
    "q": "Be where your enemy is not.",
    "a": "Sun Tzu",
    "h": "<blockquote>&ldquo;Be where your enemy is not.&rdquo; &mdash; <footer>Sun Tzu</footer></blockquote>"
  }
]

I can't seem to figure out why the error is occurring since I don't really see any issues. This is the error I am getting:

Unexpected character encountered while parsing value: A. Path '', line 0, position 0.

The error is occurring on the 7th line:

JObject quote = JObject.Parse(qarray[0]["q"].ToString());

and since the 8th line is the same I expect the same error.


Solution

  • According to JObject.Parse,

    Load a JObject from a string that contains JSON.

    For your "q" and "a", it is just a simple string but not a JSON string. Hence you should not use JObject.Parse.

    With .ToString(), it is good enough to retrieve the value of q and a.

    string quote = qarray[0]["q"].ToString();
    string author = qarray[0]["a"].ToString();
    

    Sample program