Parsing JSON in ActionScript (Adobe Flex). JSON.decode(string) returns null

12,429

Solution 1

Problem solved thanks to J_A_X (see comments to the question). Elements can be accessed by key. Example:

var obj:Object = JSON.decode(json);
trace(obj.GlossEntry[0].Acronym.toString());

Solution 2

In flex 4.5 it become parse instead of decode

var obj:Object=JSON.parse(json);

Solution 3

Try this also working

var arr:Array = (JSON.decode(json) as Array);
for (var keyname:String in arr)
{
trace ( keyname + ": " + arr[ keyname ] );          
}   
Share:
12,429
Jacek
Author by

Jacek

Updated on June 28, 2022

Comments

  • Jacek
    Jacek almost 2 years

    I am trying to parse JSON file in my Flex project. I included as3corelib.swc and imported com.adobe.serialization.json.JSON, but JSON.decode() function still returns null. What might be the problem?

    [Embed(source="assets/test.json",mimeType="application/octet-stream")]
    private var json_file:Class;
    
    public function load():void
    {
        var bytes:ByteArray = new json_file();
        var json:String = bytes.readUTFBytes(bytes.length);
        trace(json); // String is OK!
        var arr:Array = (JSON.decode(json) as Array);
        trace(arr); // Array is null!
    }
    

    I also tried:

        var str:String = (JSON.decode(json) as String);
        trace(arr); // null!
    

    and:

        var arr:Object = JSON.decode(json); // [object Object]
        trace(arr.toString()); // empty string
    

    Thanks for your time.

    • J_A_X
      J_A_X almost 13 years
      Could be either bad JSON, or you aren't using it properly. JSON uses key-value pairs and is always decoded into an object which has properties. You should access the decoded object as Object.someKey to get the data.
    • Jacek
      Jacek almost 13 years
      JSON is good. I checked it with a validator.
    • Jacek
      Jacek almost 13 years
      You are right J_A_X. I can access elements with: trace(arr.GlossEntry[0].Acronym.toString());