简体   繁体   中英

Erlang: Find data in Json

I have one predefined set of keys key1,key2 ...key10. (These keys will not change) I need to extract data from json corresponding to these keys. For example access, token, expires at:

{\"access\": {\"token\": {\"issued_at\": \"2015-09-10T12:03:49.554141\", \"expires\": \"2015-09-10T13:03:49Z\" \"id\": \"dbb60c28daf34b80905883789f698cde\", \"tenant\": {\"description\": null, \"enabled\": true,

How can I extract the value for these keys not using json libraries? Is it a good idea? (I think that overhead of parsing entire string doesn`t worth)

How big is JSON we are talking about? Is this JSON fed by chunks or is already loaded whole in the memory? If yes, why bother? How fast is fast enough for you? There is a whole bunch of question to ask before you start solving it. In most cases parsing whole JSON should be sufficient:

get_from_json(JSON, Path) ->
    path(jiffy:decode(JSON), Path).

path(Obj, []) -> Obj;
path({List}, [Key|Path]) when is_list(List) ->
    case lists:keyfind(iolist_to_binary(Key), 1, List) of
        false -> not_found;
        {_, Obj} -> path(Obj, Path)
    end;
path(_, _) -> not_found.

Otherwise, you can write your own parser. You can even use leex or existing JSON parser like jsx as starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM