Elm:
עבודה עם JSON
איך לעשות:
Elm מתייחס לטיפול ב-JSON עם מפורשות ובטיחות, בעיקר באמצעות המודולים Json.Decode וJson.Encode. כדי להתחיל לעבוד עם JSON, תצטרך להגדיר פענח לסוג הנתונים שלך. בואו נניח שאנו עוסקים באובייקט פרופיל משתמש פשוט.
ראשית, הגדר את סוג ה-Elm שלך:
type alias UserProfile =
{ id : Int
, name : String
, email : String
}פענוח JSON ל-Elm
כדי לפענח מחרוזת JSON לסוג UserProfile, צור פענח:
import Json.Decode exposing (Decoder, int, string, field, map3)
userProfileDecoder : Decoder UserProfile
userProfileDecoder =
map3 UserProfile
(field "id" int)
(field "name" string)
(field "email" string)כדי לפענח אובייקט JSON:
import Json.Decode exposing (decodeString)
jsonString : String
jsonString =
"""{"id": 1, "name": "John Doe", "email": "john@example.com"}"""
decoded : Result String UserProfile
decoded =
decodeString userProfileDecoder jsonString
{- פלט לדוגמא:
Result.Ok { id = 1, name = "John Doe", email = "[email protected]" }
-}קידוד Elm ל-JSON
כדי לקודד ערך מ-Elm חזרה ל-JSON, השתמש במודול Json.Encode.
import Json.Encode exposing (object, int, string)
encodeUserProfile : UserProfile -> String
encodeUserProfile userProfile =
object
[ ("id", int userProfile.id)
, ("name", string userProfile.name)
, ("email", string userProfile.email)
]
|> Json.Encode.encode 0
{-
שימוש:
encodeUserProfile { id = 1, name = "John Doe", email = "[email protected]" }
פלט לדוגמא:
"{"id":1,"name":"John Doe","email":"[email protected]"}"
-}ספריות צד שלישי
חבילות Elm כמו elm-json-decode-pipeline יכולות לפשט את יצירת הפענחים באמצעות סגנון צינור, שמאוד נוח לפענוח אובייקטים מורכבים.
ראשית, הוסף את הספריה לפרויקט שלך:
elm install NoRedInk/elm-json-decode-pipelineאז, אתה יכול לפשט את הגדרת הפענח כך:
import Json.Decode exposing (int, string, succeed)
import Json.Decode.Pipeline exposing (required, decode)
userProfileDecoder : Decoder UserProfile
userProfileDecoder =
decode UserProfile
|> required "id" int
|> required "name" string
|> required "email" string
{- השתמש בפענח הזה כמו קודם עם decodeString לפענוח מחרוזות JSON. -}גישה זו מפשטת את הפענח, הופכת את הקוד לנקי יותר וקל יותר לתחזוקה, במיוחד ככל שמבני הנתונים הופכים למורכבים יותר.