开发者

JSON format problem when using Factual geo data

I'm using Factual api to fetch location data. Their restful service return data in JSON format as follow, but they are not using "usual" JSON format. There's no attribute key, instead, there's a “fields” that explains all the field keys.

So the question is how to retrieve the attribute I need? Please give an example if possible. Thanks in advance.

{
    "response": {
  开发者_StackOverflow中文版      "total_rows": 2,
        "data": [
            [
                "ZPQAB5GAPEHQHDy5vrJKXZZYQ-A",
                "046b39ea-0951-4add-be40-5d32b7037214",
                "Hanko Sushi Iso Omena",
                60.16216,
                24.73907
            ],
            [
                "2TptHCm_406h45y0-8_pJJXaEYA",
                "27dcc2b5-81d1-4a72-b67e-2f28b07b9285",
                "Masabi Sushi Oy",
                60.21707,
                24.81192
            ]
        ],
        "fields": [
            "subject_key",
            "factual_id",
            "name",
            "latitude",
            "longitude"
        ],
        "rows": 2,
        "cache-state": "CACHED",
        "big-data": true,
        "subject_columns": [
            1
        ]
    },
    "version": "2",
    "status": "ok"
}


If you know the field name, and the data isn't guaranteed to stay in the same order, I would do a transform on the data so I can reference the fields by name:

var fieldIndex = {}
for (key in x.response.fields)
{
    fieldIndex[x.response.fields[key]] = key;
}

for (key in x.response.data)
{
    alert(x.response.data[key][fieldIndex.name]);
}


// Field map
var _subject_key = 0,
    _factual_id  = 1,
    _name        = 2,
    _latitude    = 3,
    _longitude   = 4;

// Example: 
alert(_json.response.data[0][_factual_id]);

Demo: http://jsfiddle.net/AlienWebguy/9TEJJ/


I work at Factual. Just wanted to mention that we've launched the beta of version 3 of our API. Version 3 solves this problem directly, by including the attribute keys inline with the results, as you would hope. (Your question applies to version 2 of our API. If you're able to upgrade to version 3 you'll find some other nice improvements as well. ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜