Vidish Joglekar
Vidish Joglekar

Reputation: 1

How to parse complex JSON Keys

How can I parse this JSON result :

{
   "Output": [
      {
         "LGA11aAust.DistanceToBorder": "2587.4",
         "LGA11aAust.LGA_NAME": "Hume (C)",
         "SustainabilityVicZones.DistanceToBorder": "2575.6",
         "SustainabilityVicZones.REBATEZN": "Metropolitan Melbourne",
         "LGA11aAust.Status": "T",
         "SustainabilityVicZones.Status": "T",
         "Status": "T",
         "Status.Code": "",
         "Status.Description": "",
         "user_fields": []
      }
   ]
}

I am aware of JSON.parse method but with that I cannot access the values of the keys as they have a . in them.

E.g.: I cannot use Output[0].Status.Code as it does not treat Status.Code as a whole, it thinks that the Code is under the Status field.

Please help.

Upvotes: 0

Views: 780

Answers (4)

Vidish Joglekar
Vidish Joglekar

Reputation: 1

I found out the answer to my question.

Instead of using a (.) Dot operator, we can directly write the name of the parameter in square brackets.

Eg:- The value of the parameter 'Status.Code' can be accessed as follows-

 Output[0]["Status.Code"]  

Upvotes: 0

Preben Huybrechts
Preben Huybrechts

Reputation: 6141

You could use JSON .NET my favorite JSON serializer and deserializer.

How to use:



public class Output
{
   [JsonProperty(PropertyName="LGA11aAust.DistanceToBorder")]
   public decimal DistanceToBorder {get; set;}

   //All the other properties

}

Usage:

var deserializedObjects = 
JsonConvert.DeserializeObject<List<Output>>(someJsonResult)

Upvotes: 1

Renju Vinod
Renju Vinod

Reputation: 254

Check this

Dynamic JSON Parser

Upvotes: 0

gerrod
gerrod

Reputation: 6637

It sounds like a bad idea... but I think you can do it if you escape the periods with a slash:

JSON.parse('{"a\.b":"c"}')

Gives:

Object
    a.b: "c"

(in the Chrome debugger)

You'd then have to use quotes to access your properties, as such:

var x = JSON.parse('{"a\.b":"c"}');
console.log(x["a.b"]);

Upvotes: 0

Related Questions