SOLVED Struggling with reading complex JSON structure

TomOmNom

Member
Hey! I had another problem like this before and the solution completely went over my head so I have another related problem with no knowledge of how to fix it.
I'm trying to access the value "name" from this JSON but I don't know how to read it.
JSON:
{
"Types": [
  {
   "name": "Attribute"
  }
]
}
Why is the JSON in this format? because I'm storing a LOT of json here and can't really change the structure.
Here's the code that DOESN'T work
GML:
var file = file_text_open_read("power_types.json")
var str = file_text_read_string(file)
file_text_close(file)
var root = json_decode(str)
var k = ds_map_find_value(ds_list_find_value(root[?"default"],0),"name")
The error returns root[?"default"] as a this string {.
All help welcome
 

rui.r6o

Member
Take a look at the manual entry for json_decode, specifically this part:
  • JSON is a single value - returns a DS map with a single entry "default" that is the value
  • JSON is an array of objects or values - returns a DS map with a single entry "default" that is a DS list of the objects or values
  • JSON is an object - returns a DS map that has the object entries in it
In your case the top level element is a JSON object, meaning that it will be available directly as the root DS Map. This root DS Map will then have an entry called Types mapped to a DS List. Hopefully this will allow you to understand how to reach the proper value, if not I can try to clarify it a bit further without posting the final code immediately.
 

TomOmNom

Member
I'm pretty sure I tried this as well, but the value assigned to Types just comes back as undefined, not a list index. I can't figure out how to fix this.
 

rui.r6o

Member
Could you use the debugger or print out the contents of the string to check that the string is indeed the JSON you are expecting? If not, can you post the actual JSON being read?
 
Did you create that JSON file with the ds_map and ds_list functions in GMS? Or is it just a random JSON file? I'd be trying json_parse() before json_decode().
 

FrostyCat

Redemption Seeker
Your file-reading portion only gives you the first line, so the { character is the only thing that got into json_decode. You have to read the whole file for it to count, just the first line won't cut it.

With json_decode:
GML:
var jsonstr = "";
for (var f = file_text_open_read("power_types.json"); !file_text_eof(f); file_text_readln(f)) {
    jsonstr += file_text_read_string(f);
}
file_text_close(f);
var root = json_decode(jsonstr);
var k = root[? "Type"][| 0][? "name"];
With json_parse
GML:
var jsonstr = "";
for (var f = file_text_open_read("power_types.json"); !file_text_eof(f); file_text_readln(f)) {
    jsonstr += file_text_read_string(f);
}
file_text_close(f);
var root = json_parse(jsonstr);
var k = root.Type[0].name;
 
Top