Getting Keys from a JObject

Oct 18, 2010 at 9:08 PM

I must seriously be missing something.  I've searched the forums and can't figure this out.  I want to something that seems to be fairly simple.  I want to get the keys for my JObject.

I have something like this:

{"lookups"[
        {
          "4""#  of MLS #",
          "56""# Beds [Avg]",
          "34""List Prc [Avg]",
          "30""List Prc [Sum]",
          "55""CDOM  [Avg]"
        }
      ]}

 

I don't know the names of the keys before hand.  I'd like to do something like

foreach(string ThisKey in ThisJObject.Keys){

MyList.Add(ThisJObject[ThisKey]);

}

I've seen that JObjects are just dictionaries but I've tried casting them as such and the code will not compile.

Coordinator
Oct 19, 2010 at 8:13 AM

A JObject has a Properties method. You can use that to get property names with the following LINQ:

IList<string> propertyNames = TheJObject.Properties().Select(p => p.Name).ToList();

Oct 19, 2010 at 2:04 PM

Ok. Duh.  That makes way too much sense.  Thanks for the reply.

Sep 19, 2011 at 9:41 PM

Does anyone have a conversion of that C# LINQ code into VB.NET? I'm sort of a newbie using LINQ. As the original post said, this seems like such a basic function to be able to get this information that we shouldn't have to use calls within "properties" to get this... if a JObject returns a "count", it seems to me that you should be able to access each element within the JObject via index, not just via name... so that you can loop thru the JObject much like an array.

Oct 11, 2011 at 8:25 PM

There you have :)

Dim propertyNames As IList(Of String) = TheJObject.Properties().Select(Function(p) p.Name).ToList();
Sep 20, 2012 at 10:15 PM

Hi i have a similar problem, but i'm using dotnet classes in MAXscript everyting is fine but the "Select(p => p.name)" part does not work. It is asking me for <factor> can you explain me what is it "p => p.name" and how would i possibly introduce it to maxscript. I even tried to create a function accepting a p value and returning p.name but it didnot work. Your help will be most wellcome.

Sep 20, 2012 at 10:18 PM
Edited Sep 20, 2012 at 10:22 PM

 

 

dotnet.loadAssembly "Newtonsoft.Json.dll"
  
JObjClass =dotnetClass "Newtonsoft.Json.Linq.JObject"
JObj = dotnetObject JObjClass

dsffilename = @"d:\Users\Serkan\Desktop\takoz\takoz.dsf"


dsfFile = openfile dsfFilename
dsf = ""

while not eof dsffile do
(	
	line = readline dsffile		
	append dsf line

	continue
)

o = JObj.parse dsf


print o.item["scene"].item["materials"].count 
print o.item["scene"].item["materials"].item[0].item["type"].value 

function func p = 
(
	return p.name
)

print (o.properties().select( func(p) ).toList())
Sep 20, 2012 at 10:19 PM

This is how the code looks like, maybe syntax will remind you some other language.