0

I have JSON that has to conform to this standard.

{
  "level": [
    {
      "1": {
        "Title": "My First Title",
        "Body": "My First Body"
      }
    },
    {
      "2": {
        "Title": "My Second Title",
        "Body": "My Second Body"
      }
    }
}

Whilst I know it's not the best formed JSON in the world, it has to stay like this for integration into a complex system. I have not been successful in finding a way of querying everything inside the "first level". I only need to ever strip the json by the "1", "2", "3", keys.

The SQL equivilant would be:

SELECT Title, Body FROM level WHERE level.id = 1.

I'm struggling because there is no id. the key is the id therefore I do not know what to search on.

Returned JSON should be:

{
    "Title": "My First Title",
    "Body": "My First Body"
}
Nicholas Mordecai
  • 859
  • 2
  • 12
  • 33

3 Answers3

1

This will return an Array with matches:

var queryID = "1";

yourJSON.level.filter(function(row){ return queryID in row; })
Kosmas Papadatos
  • 1,277
  • 2
  • 14
  • 32
0

Since you brought up SQL... You could use linq.js

var data = {
  "level": [
    {
      "1": {
        "Title": "My First Title",
        "Body": "My First Body"
      }
    }, {
      "2": {
        "Title": "My Second Title",
        "Body": "My Second Body"
      }
    }
  ]
};

Now, for example:

var result = Enumerable.From(data.level)
    .Where("$.hasOwnProperty(1)")
    .FirstOrDefault(null);

result;
// {"1":{"Title":"My First Title","Body":"My First Body"}}

or

var result = Enumerable
    .From(data.level)
    .Select(function ($) {
        var keys = Object.keys($);
        return {
            id: keys[0],
            value: $[keys[0]]
        };
    })
    .Where("$.id == 1")
    .Select("$.value")
    .FirstOrDefault(null);

result; 
// {"Title":"My First Title","Body":"My First Body"}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
0

I am assuming you want all of that as an array of objects:

var levels = [];
json["level"].forEach(function (val) {
      Object.keys(val).forEach(function (key) {
          levels[key] = val[key];
      });
});

now if you query level[id] you should get the desired result.

See this example: https://jsfiddle.net/c2vk5c6m/

Arathi Sreekumar
  • 2,544
  • 1
  • 17
  • 28