Waleed
Waleed

Reputation: 1188

Iterating JObject Keys

I have the following JObject as return by https://gate.io/api2#trade API. How do I iterate through each key which is a separate coin also get its value.

I tried to parse it using Newtonsoft JObject Parse like this:

var coinData = JObject.Parse(@"{
    ""result"": ""true"",
    ""available"": {
        ""BTC"": ""0.83337671"",
        ""LTC"": ""94.364"",
        ""ETH"": ""0.07161"",
        ""ETC"": ""82.35029899""
    },
    ""locked"": {
        ""BTC"": ""0.0002"",
        ""YAC"": ""10.01""
    }
}")["available"];

foreach (JToken item in coinData)
{
    item.Key
}

but then JToken doesn't give access to key values. I don't know how to further parse it.

JSON received from gateio api:

{
    "result": "true",
    "available": {
        "BTC": "0.83337671",
        "LTC": "94.364",
        "ETH": "0.07161",
        "ETC": "82.35029899"
    },
    "locked": {
        "BTC": "0.0002",
        "YAC": "10.01"
    }
}

EDIT: Should I break it with ':' while iterating in loop? This is working if i break it and replace quotes.

foreach (JToken item in coinData)
{
    var data = item.ToString().Replace("\"", String.Empty).Split(':');
}

var data has two parts, 1 => coin name, 2 => balance.

Is there any other legit way?

Upvotes: 3

Views: 4797

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500635

I would suggest being very explicit about expecting the result of "available" to be another object, by casting to JObject. You can then call Properties() to get its properties, each as a JProperty. Here's a complete example to demonstrate:

using System;
using Newtonsoft.Json.Linq;

class Program
{
    public static void Main()        
    {
        string json = @"{
            'result': 'true',
            'available': {
                'BTC': '0.83337671',
                'LTC': '94.364',
                'ETH': '0.07161',
                'ETC': '82.35029899'
            },
            'locked': {
                'BTC': '0.0002',
                'YAC': '10.01'
            }
        }".Replace('\'', '"');
        JObject root = JObject.Parse(json);
        JObject coins = (JObject) root["available"];
        foreach (JProperty property in coins.Properties())
        {
            string name = property.Name;
            string value = (string) property.Value;
            Console.WriteLine($"Name: {name}; Value: {value}");
        }    
    }
}

Upvotes: 2

Evk
Evk

Reputation: 101483

JToken is base class for all types of json tokens. In your case though you want only json properties, so you need to filter by more narrow type - JProperty. You can filter to include only property tokens like this:

foreach (var item in coinData.OfType<JProperty>()) {
    string coinName = item.Name;
    // to parse as decimal
    decimal balance = item.Value.Value<decimal>();
    // or as string
    string balanceAsString = item.Value.Value<string>();
}

Upvotes: 5

Related Questions