تحليل JSON
حوّل النص إلى قيم JSON
تحليل JSON درس مجاني في Scala for Backend Engineering & Functional Programming على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Scala for Backend Engineering & Functional Programming، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Scala for Backend Engineering & Functional Programming 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Circe?
Circe is a popular JSON library for Scala, built on top of the cats functional ecosystem.
It favors type-safety and immutability: parsing returns an Either rather than throwing, and decoding produces typed values instead of untyped maps.
This lesson covers turning raw JSON text into Circe's Json model.
Adding the Dependency
Circe ships as several modules. For parsing and the core model you need circe-core and circe-parser.
The circe-generic module adds automatic codec derivation, covered in later lessons.
libraryDependencies ++= Seq(
"io.circe" %% "circe-core" % "0.14.6",
"io.circe" %% "circe-parser" % "0.14.6"
)The parse Function
The entry point for reading JSON is io.circe.parser.parse.
It takes a String and returns Either[ParsingFailure, Json]. The left side captures syntax errors; the right side holds the parsed tree.
import io.circe.parser._
val result = parse("{\"name\": \"Ada\", \"age\": 36}")
// result: Either[ParsingFailure, Json]Handling Parse Failures
Because parse returns an Either, you handle errors explicitly with pattern matching or combinators instead of try/catch.
A ParsingFailure includes a human-readable message describing the syntax problem.
parse("{ not valid }") match {
case Right(json) => println(json)
case Left(err) => println(s"Failed: ${err.message}")
}The Json Model
A successfully parsed value is a Json — an immutable tree representing one of six JSON types: object, array, string, number, boolean, or null.
You inspect it with predicates like isObject or fold over its shape.
val json = parse("[1, 2, 3]").getOrElse(Json.Null)
println(json.isArray) // true
println(json.isObject) // falseNavigating with the Cursor
To read into nested data, call .hcursor on a Json value. The HCursor is a zipper that lets you move through the tree.
Use downField to descend into an object key.
val json = parse("{\"user\": {\"name\": \"Ada\"}}").toOption.get
val cursor = json.hcursor
val name = cursor.downField("user").downField("name").as[String]
// name: Either[DecodingFailure, String] = Right(Ada)Extracting Values with as
Once positioned, .as[A] attempts to decode the focused value into type A.
It returns Either[DecodingFailure, A], so a type mismatch is reported as a value, not an exception.
val json = parse("{\"age\": 36}").toOption.get
val age = json.hcursor.downField("age").as[Int]
println(age) // Right(36)parse vs decode
Use parse when you want the raw Json tree to inspect manually.
Use decode[A] when you want to go straight from String to a typed value A in one step. It combines parsing and decoding.
import io.circe.parser.decode
val n: Either[io.circe.Error, Int] =
decode[Int]("42")
println(n) // Right(42)Optional Fields
Real-world JSON often has missing keys. The cursor method get[A] on a downed field fails if absent, while getOrElse supplies a default.
Decoding into Option[A] treats a missing or null field as None.
val json = parse("{\"name\": \"Ada\"}").toOption.get
val nick = json.hcursor.get[Option[String]]("nickname")
println(nick) // Right(None)Parsing Arrays
You can decode a JSON array directly into a Scala collection by asking for List[A] or Vector[A].
Circe maps each element and short-circuits with a DecodingFailure if any element is the wrong type.
import io.circe.parser.decode
val xs = decode[List[Int]]("[1, 2, 3]")
println(xs) // Right(List(1, 2, 3))Pretty Printing
Any Json value renders back to text with .noSpaces for compact output or .spaces2 for indented output.
This round-trips parsed data and is handy for logging or debugging.
val json = parse("{\"a\":1,\"b\":2}").toOption.get
println(json.noSpaces)
println(json.spaces2)Quick Check
Test your understanding of Circe parsing.
Recap
You learned to turn JSON text into Circe's model. parse yields Either[ParsingFailure, Json]; decode[A] goes straight to a typed value.
The HCursor navigates with downField, and .as[A] extracts typed values. Failures are values, not exceptions.
الأسئلة الشائعة
هل درس «تحليل JSON» مجاني؟
نعم — نص درس «تحليل JSON» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Scala for Backend Engineering & Functional Programming، انتقل إلى CoddyKit PRO. تتضمن دورة Scala for Backend Engineering & Functional Programming 4 دروس في المجموع.
ماذا ستتعلم في «تحليل JSON»؟
حوّل النص إلى قيم JSON تتمرن على Scala for Backend Engineering & Functional Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Scala for Backend Engineering & Functional Programming؟
لا تُشترط خبرة سابقة. Scala for Backend Engineering & Functional Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «تحليل JSON»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Scala for Backend Engineering & Functional Programming هذا؟
نعم. كل درس في Scala for Backend Engineering & Functional Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.