[Python] Parse JSON in scala and do get with deault value

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    Sample JSON read from file:

    {
    "category": "[{\"a\":3,\"b\":11,\"c\":86}]",
    "ids": "[\"1234\", \"5678\"]",
    "uid": "55555",
    "flag": true
    }


    Current Code:

    val filePath = args(0)
    val jsonFileString = Source.fromFile(filePath).getLines.mkString.stripMargin
    val mapper = new ObjectMapper().registerModules(DefaultScalaModule)
    val jsonStringObj = mapper.readTree(jsonFileString)
    val ids = jsonStringObj.get("ids").asText()


    This works fine to get me the ids when the json file contains it, but I want to provide a default value in case the key "ids" is not present in the JSON file. How do I do that?

    In python I could do something like json_dict.get('ids', 'default_value'). I am looking for an equivalent.

    Continue reading...

Compartilhe esta Página