1

I'm using the JSON.NET serializer with Entity Framework and have run into a situation where the JSON being outputted has these "special properties" included such as $id and $ref. From what I've read, these properties are used by pure JSON to condense the JSON outputted so that the repeated element does not have to be written twice.

So, the JSON that gets outputted is something like this:

 var myArray = [
     {
         "ActiveStates": [
             {
                 "$id": "1",
                 "StateID": "CA",
                 "Name": "California"
             },
             {
                 "$id": "2",
                 "StateID": "NV",
                 "Name": "Nevada"
             }
         ],
         "DefaultState": {
             "$ref": "1"
         }
     }
 ];

Using Javascript, how can I use the $ref from DefaultState and $id from AvailableStates to return the Name of California?

I'm thinking something with logic similar to myArray.find(myArray.DefaultState.$ref).Name; which might return California.

Hopefully this is something easy like this.

EDIT: I would also consider it an acceptable answer to learn how to disable these "special properties" from being rendered to the array even if it means that the JSON outputted will be longer due to the duplicated elements.

jaressloo
  • 210
  • 3
  • 13

2 Answers2

1

I found the solution to my problem: https://stackoverflow.com/a/4992429/1322509

I'm using the getObjects function defined below as found on the page link above.

var myArray = [
    {
    "AvailableStates": [
        {
        "$id": "1",
        "CityID": "CA",
        "Name": "California"},
    {
        "$id": "2",
        "CityID": "NV",
        "Name": "Nevada"}
    ],
    "DefaultState": {
        "$ref": "1"
    }}
];

var stateName = getObjects(myArray, '$id', myArray[0].DefaultState.$ref)[0].Name;

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}​
Community
  • 1
  • 1
jaressloo
  • 210
  • 3
  • 13
  • Wrote a longer blog post about this here: http://www.jaressloo.com/2012/05/using-jsons-special-properties-of-ref-and-id/ – jaressloo May 04 '12 at 20:58
0

I managed to disable it in the config (NewtonSerialiser)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = 
        Newtonsoft.Json.PreserveReferencesHandling.None;
    }
 }
amine
  • 320
  • 3
  • 7