2017-10-09 9 views
0

중첩 된 JSON 응답에서 URL을 찾고 매핑하려고합니다. 내 기능은 지금까지 다음과 같습니다Elixir : 중첩 된 JSON의 값 접두사로 찾기

def list(env, id) do 
    Service.get_document(env, id) 
    |> Poison.decode! 
    |> Enum.find(fn {_key, val} -> String.starts_with?(val, 'https') end) 
end 

같은 JSON 데이터가 거의 같습니다

"stacks": [ 
    { 
     "boxes": [ 
     { 
      "content": "https://ddd.cloudfront.net/photos/uploaded_images/000/001/610/original/1449447147677.jpg?1505956120", 
      "box": "photo" 
     } 
     ] 
    } 
    ], 
    "logo": "https://ddd.cloudfront.net/users/cmyk_banners/000/000/002/original/banner_CMYK.jpg?1397201875" 

그래서 URL은 어떤 키를 가지고 있고, 모든 수준에서 할 수 있습니다. 그 코드와

는이 오류를 얻을 :

no function clause matching in String.starts_with?/2 

누구나 JSON 응답에서 찾을 수있는 더 좋은 방법이있어?

답변

3

당신은 세 가지 유형의 데이터 처리 이에 대한 재귀 기능을 사용해야합니다 : 맵에 대한

  1. 를, 그것은 모든 가치를 통해 재귀.
  2. 목록의 경우 모든 요소에 대해 반복됩니다.

    defmodule A do 
        def recursive_starts_with(thing, start, acc \\ []) 
    
        def recursive_starts_with(binary, start, acc) when is_binary(binary) do 
        if String.starts_with?(binary, start) do 
         [binary | acc] 
        else 
         acc 
        end 
        end 
        def recursive_starts_with(map, start, acc) when is_map(map) do 
        Enum.reduce(map, acc, fn {_, v}, acc -> A.recursive_starts_with(v, start, acc) end) 
        end 
        def recursive_starts_with(list, start, acc) when is_list(list) do 
        Enum.reduce(list, acc, fn v, acc -> A.recursive_starts_with(v, start, acc) end) 
        end 
    end 
    
    data = %{ 
        "stacks" => [ 
        %{ 
         "boxes" => [ 
         %{ 
          "content" => "https://ddd.cloudfront.net/photos/uploaded_images/000/001/610/original/1449447147677.jpg?1505956120", 
          "box" => "photo" 
         } 
         ] 
        } 
        ], 
        "logo" => "https://ddd.cloudfront.net/users/cmyk_banners/000/000/002/original/banner_CMYK.jpg?1397201875" 
    } 
    
    data |> A.recursive_starts_with("https") |> IO.inspect 
    

    출력 :

    ["https://ddd.cloudfront.net/photos/uploaded_images/000/001/610/original/1449447147677.jpg?1505956120", 
    "https://ddd.cloudfront.net/users/cmyk_banners/000/000/002/original/banner_CMYK.jpg?1397201875"] 
    
    문자열을
  3. , 그것은 여기

starts_with? 확인하는 용어와 문자열을 받아 간단한 구현의 "HTTPS"로 시작하는 문자열을 선택

+0

이것은 대단한 도움이 될만한 가치가 있습니다. 다시. –