0

I'm trying to print a single JObject as a CSV row

for example:

{"result": {
"id": "24095",
"hostid": "24094",
"name": "host1.fqdn.com",
"ipaddress" : "192.168.1.184"
}
}

as

id,hostid,name,ipaddress
24095,24094,host1.fqdn.com,192.168.1.184

I can easily iterate through the object with

foreach (var item in jobj) {
   Console.Write(item.Key + ",");
}

but I end up with a , at the end of the header

I tried

for (int i = 0; i < jobj.Count; i++)...

but I'm having trouble accessing i.Key. I'm doing something wrong here but i'm not sure what.

Any ideas on how i can print all the keys in an object as a CSV minus a , at the end?

Thank you.

2 Answers 2

1

Try the following code.

string result = string.Empty;

foreach (var item in jobj)
{
    if (!string.IsNullOrEmpty(result))
    {
        result += ",";
    }
    result += item.Key;
}
Console.WriteLine(result);
Sign up to request clarification or add additional context in comments.

Comments

1

Iterate over all except the last one, then use the last one outside the block.

for (int i = 0; i < jobj.Count-1; i++) {
    Console.Write(jobj[i].Key + ", ");
}

Console.WriteLine(jobj[jobj.Count-1].Key);

2 Comments

Hi. Thanks for answering. I have no trouble iterating over all the items but I'm trying to get just the keys. Not the values. So jobj[i].key is what i'm after but it's not available as a property.
I dont recognise JObject, what is it apart of?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.