Getting json value out of array

Talk about whatever topic you'd like, RPG related or not. (But please discuss things related to our software in the Tools section, below.)

Moderators: dorpond, trevor, Azhrei

Post Reply
paracharlie
Kobold
Posts: 4
Joined: Wed Feb 27, 2013 3:50 pm

Getting json value out of array

Post by paracharlie »

Having this property to evaluate:
ability:[["Strength",10,0,1],["Constitution",10,0,1]]

How would I get the value of both stats which is 10 and add them together?
I'm having a hard time wrapping my brain around this multi array.

User avatar
aliasmask
RPTools Team
Posts: 9024
Joined: Tue Nov 10, 2009 6:11 pm
Location: Bay Area

Re: Getting json value out of array

Post by aliasmask »

I wouldn't store it that way. Try to avoid nesting jsons when possible. You could use a json object with string properties.

Code: Select all

stats:{"Strength":"value=10;var2=0;var3=1","Constitution":"value=10;var2=0;var3=1"}
But to answer your question, you can do this:

Code: Select all

[H: StrPlusCon = json.get(json.get(ability,0),1) + json.get(json.get(ability,1),1)]
Other than my naming convention, it's difficult to know what's going on. To wrap your head around the order of the json.get, first get the big thing (the outside array), then wrap in another json.get to get the 2nd dimension and so on. So, json.get(ability,0) = ["Strength",10,0,1] but we'll call it X. And the outside get is json.get(X,1). 0 is the first element in array and 1 is the 2nd element.

Now if the data was set up like my suggestion it would look like this:

Code: Select all

[H: StrPlusCon = getStrProp(json.get(stats,"Strength"),"value") + getStrProp(json.get(stats,"Constitution"),"value")]
What is being done is now more obvious because we put in some naming for the variables.

paracharlie
Kobold
Posts: 4
Joined: Wed Feb 27, 2013 3:50 pm

Re: Getting json value out of array

Post by paracharlie »

Oh I see, so your calling twice in the same function to access the index because it's nested? I think I understand.

User avatar
CoveredInFish
Demigod
Posts: 3104
Joined: Mon Jun 29, 2009 10:37 am
Location: Germany
Contact:

Re: Getting json value out of array

Post by CoveredInFish »

Yes, but dont miss the point

a) You might be better of using an "outside" object instead of an array. You'll probably will access the attributes by name much more often than in sequential order - so an object is more suited. Choosing the correct data structure is very essential to your coding.

b) nesting jsons is somewhat problematic (mostly performance wise), so rethink if there is an alternative (like using a strprop list inside)

paracharlie
Kobold
Posts: 4
Joined: Wed Feb 27, 2013 3:50 pm

Re: Getting json value out of array

Post by paracharlie »

Ok thanks for your help, all very good points thank you

Post Reply

Return to “General Discussion”