how to convert from JSON to a parametric nested struct in julia? - json

stringtest="""{ "struct_A": {
"arg1": {
"arg_B": 90
},
"arg2": 100
}
}"""
jsonDict=JSON.parse(stringtest)
struct struct_B<: myStruct
arg
end
struct struct_A{T<:myStruct}
arg1::T
arg2
function BatteryStorage{T}(arg1,arg2) where {T}
return new{T}(arg1,arg2)
end
end
to_struct=ToStruct.tostruct(struct_A,jsonDict)
why I'm always getting :
LoadError: MethodError: no method matching struct_A(::Dict{String, Any})
caused by: MethodError: Cannot convert an object of type
Dict{String, Any} to an object of type
struct_A
Closest candidates are:
convert(::Type{T}, ::T) where T at essentials.jl:205

Related

How to convert Json objects into arrays [(string, double)] in Scala JSON4s?

I don't know how to use CustomSerializer to convert JSON to Scala data
I don't need to serialize the parts, but deserialization is difficult
Can someone help me? Thank you very much
{
"parameters": {
"field_owner": true,
"sample_field": "gender",
"sample_strategy": "by_ratio",
"sample_config": [["male", 1500.0], ["female", 1500.0]],
"with_replacement": true,
"random_seed": 114514,
"least_sample_num": 100
},
"input_artifacts": {"dataset": {"object_id": "upload/ml_classifier_predict_result"}},
"output_artifacts": {"predict_result": {"object_id": "ingest_output.csv"}}
}
class TupleSerializer extends CustomSerializer[(String,Double)](tuple_formats => (
{
case JArray(List(JString(x), JDouble(y))) =>
(x,y)
},{
case x:Tuple2[String,Double] => null
}
))
implicit val formats: Formats = DefaultFormats + new TupleSerializer
val fileBuffer = Source.fromFile(path)
val jsonString = fileBuffer.mkString
parse(jsonString).extract[StratifiedSampleArgument]
}
error message:
o usable value for parameters
No usable value for sample_config
Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
Caused by: org.json4s.package$MappingException:
No usable value for sample_config
Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
Caused by: org.json4s.package$MappingException: Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] StratifiedSampleDriverTest.main:15 » Mapping No usable value for parameters
No...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

Returns an unknown type in Rust

From a deserialized JSON file into structures,
{
"infos": {
"info_example": {
"title": {
"en": "Title for example",
"fr": "Titre pour l'exemple"
},
"message": {
"en": "Message for example"
}
}
},
"errors": {}
}
#[derive(Debug, Deserialize)]
struct Logs {
infos: Infos,
errors: Errors,
}
#[derive(Debug, Deserialize)]
struct Infos {
info_example: Log,
}
#[derive(Debug, Deserialize)]
struct Errors {}
#[derive(Debug, Deserialize)]
struct Log {
title: MultiString,
message: MultiString,
}
#[derive(Debug, Deserialize)]
struct MultiString {
en: String,
fr: Option<String>,
de: Option<String>
}
I would like to create a function working like this :
logs_manager.get("infos.info_example.message.en")
struct LogsManager {
logs: Logs
}
impl LogsManager {
fn get(&self, element: &str) -> T {
let splitted: Vec<&str> = element.split(".").collect();
// Later it will be a loop, but for now I'm just gonna take the first part
match splitted[0] {
"infos" => {
&self.logs.infos
},
"errors" => {
&self.logs.errors
}
_ => panic!()
}
}
}
When I try to compile, I'm getting these errors :
Compiling so_question_return_type v0.1.0 (/run/media/anton/data120/Documents/testa)
error[E0308]: mismatched types
--> src/main.rs:26:17
|
20 | fn get<T>(&self, element: &str) -> &T {
| - this type parameter -- expected `&T` because of return type
...
26 | &self.logs.infos
| ^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `Infos`
|
= note: expected reference `&T`
found reference `&Infos`
error[E0308]: mismatched types
--> src/main.rs:29:17
|
20 | fn get<T>(&self, element: &str) -> &T {
| - this type parameter -- expected `&T` because of return type
...
29 | &self.logs.errors
| ^^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `Errors`
|
= note: expected reference `&T`
found reference `&Errors`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `so_question_return_type` due to 2 previous errors
try compile by yourself thanks to this file : https://gist.github.com/antoninhrlt/feee9ec4da1cb0edd0e7f426a6c744b0
So, I've tried to create an enum variant to avoid the type return problem.
enum LogObject<'a> {
Logs(Logs),
Infos(Infos),
Errors(Errors),
Log(Log),
MultiString(MultString)
}
Then I wrap the object I want to return into a LogObject. See :
"infos" => {
StringsObject::Logs(&self.logs.infos)
}
It works. But I would like to easily retrieve the value inside the enum object.
impl<'a> LogsObject<'a> {
fn retrieve_object<T>(&self) -> &T {
match *self {
Self::Logs(object) => object,
Self::Infos(object) => object,
Self::Errors(object) => object,
Self::Log(object) => object,
Self::MultiString(object) => object,
}
}
}
But this gives me another error :
error[E0308]: mismatched types
--> crates/strings/src/manager.rs:63:44
|
61 | fn retrieve_object<T>(&self) -> &T {
| - -- expected `&T` because of return type
| |
| this type parameter
62 | match *self {
63 | Self::Logs(object) => object,
| ^^^^^^ expected type parameter `T`, found struct `structured::Logs`
|
= note: expected reference `&T`
found reference `&structured::Logs`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `strings` due to previous error
I'm lost, I don't know how to implement that. So after searching for a while, I'm asking to you.
Does anyone know how to do this ?
PS : I'm using serde for deserialization.
Making a get function was a bad idea.
Now, I'm simply doing something like that :
logs_manager.logs.info_example.message.en
Other thing, I'm including the json file into the binary thanks to include_str!
Thank you the reply, but I think it's better to abandon my first idea

JSON Object Property with space in Scala using Json4s(Jackson)

I have a JSON String in the given below form:
var jStr =
""" {
|"company":{
|"company name":"ABCD"
|},
|"person":[
|{"name":"john",
|"age":"28"
|},
|{
|"name":"AWQ",
|"age":"45"
|}
|]
|}
""".stripMargin
See the property "company name". Due to this I cannot extract it from its json form to its case class without changing the "company name" to "company_name"(or anything else). Below is the code:
import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import org.json4s._
import org.json4s.native.JsonMethods._
val parseJson = parse(jStr)
var obj = parseJson.extract[Info] // Exception Here
case class Company(cname : String)
case class Info(company: Company,person: List[Person])
case class Person(name : String , age : String)
I tried using #JsonProperty and #JsonCreator but they too failed.
#JsonCreator
case class Company( #JsonProperty("company name") cname : String)
case class Info(company: Company, person: List[Person])
case class Person(name : String , age : String)
I need to map a json property having spaces to its respective case class(which obviously can't have a space!) using Json4s in Scala.
Stacktrace:
Exception in thread "main" org.json4s.package$MappingException: No usable value for company
No usable value for cname
Did not find value which can be converted into java.lang.String
at org.json4s.reflect.package$.fail(package.scala:95)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:548)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$3.applyOrElse(Extraction.scala:572)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$3.applyOrElse(Extraction.scala:570)
at scala.PartialFunction.$anonfun$runWith$1$adapted(PartialFunction.scala:145)
at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
at scala.collection.TraversableLike.collect(TraversableLike.scala:407)
at scala.collection.TraversableLike.collect$(TraversableLike.scala:405)
at scala.collection.AbstractTraversable.collect(Traversable.scala:108)
at org.json4s.Extraction$ClassInstanceBuilder.instantiate(Extraction.scala:570)
at org.json4s.Extraction$ClassInstanceBuilder.result(Extraction.scala:630)
at org.json4s.Extraction$.$anonfun$extract$10(Extraction.scala:416)
at org.json4s.Extraction$.$anonfun$customOrElse$1(Extraction.scala:637)
at scala.PartialFunction.applyOrElse(PartialFunction.scala:127)
at scala.PartialFunction.applyOrElse$(PartialFunction.scala:126)
at scala.PartialFunction$$anon$1.applyOrElse(PartialFunction.scala:257)
at org.json4s.Extraction$.customOrElse(Extraction.scala:637)
at org.json4s.Extraction$.extract(Extraction.scala:408)
at org.json4s.Extraction$.extract(Extraction.scala:40)
at org.json4s.ExtractableJsonAstNode.extract(ExtractableJsonAstNode.scala:21)
at JsonTest.convertToJSON(JsonTest.scala:100)
at Main$.main(Main.scala:8)
at Main.main(Main.scala)
Caused by: org.json4s.package$MappingException: No usable value for cname
Did not find value which can be converted into java.lang.String
at org.json4s.reflect.package$.fail(package.scala:95)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:548)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$3.applyOrElse(Extraction.scala:572)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$3.applyOrElse(Extraction.scala:570)
at scala.PartialFunction.$anonfun$runWith$1$adapted(PartialFunction.scala:145)
at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
at scala.collection.TraversableLike.collect(TraversableLike.scala:407)
at scala.collection.TraversableLike.collect$(TraversableLike.scala:405)
at scala.collection.AbstractTraversable.collect(Traversable.scala:108)
at org.json4s.Extraction$ClassInstanceBuilder.instantiate(Extraction.scala:570)
at org.json4s.Extraction$ClassInstanceBuilder.result(Extraction.scala:630)
at org.json4s.Extraction$.$anonfun$extract$10(Extraction.scala:416)
at org.json4s.Extraction$.$anonfun$customOrElse$1(Extraction.scala:637)
at scala.PartialFunction.applyOrElse(PartialFunction.scala:127)
at scala.PartialFunction.applyOrElse$(PartialFunction.scala:126)
at scala.PartialFunction$$anon$1.applyOrElse(PartialFunction.scala:257)
at org.json4s.Extraction$.customOrElse(Extraction.scala:637)
at org.json4s.Extraction$.extract(Extraction.scala:408)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:534)
... 23 more
Caused by: org.json4s.package$MappingException: Did not find value which can be converted into java.lang.String
at org.json4s.reflect.package$.fail(package.scala:95)
at org.json4s.Extraction$.$anonfun$convert$2(Extraction.scala:735)
at scala.Option.getOrElse(Option.scala:189)
at org.json4s.Extraction$.convert(Extraction.scala:735)
at org.json4s.Extraction$.$anonfun$extract$10(Extraction.scala:410)
at org.json4s.Extraction$.$anonfun$customOrElse$1(Extraction.scala:637)
at scala.PartialFunction.applyOrElse(PartialFunction.scala:127)
at scala.PartialFunction.applyOrElse$(PartialFunction.scala:126)
at scala.PartialFunction$$anon$1.applyOrElse(PartialFunction.scala:257)
at org.json4s.Extraction$.customOrElse(Extraction.scala:637)
at org.json4s.Extraction$.extract(Extraction.scala:408)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:534)
... 42 more
Process finished with exit code 1

how to convert a JSON-String to multiple Structs in Julia

I have the following JSON-String:
jsonString="""{
"struct1": {
"arg1": 218650.27,
"arg2": 90
},
"struct2": {
"arg1": 346.4
}
}"""
I know already how to convert a JSON-String to a struct, but not a multiple struct like the JSON File above.
Is there any Pkg that helps in this case, or I have to split the JSON file?
You can parse JSON to get a dictionary of objects using JSON3:
julia> u = JSON3.read_json_str(jsonString)
JSON3.Object{Base.CodeUnits{UInt8, String}, Vector{UInt64}} with 2 entries:
:struct1 => {…
:struct2 => {…
julia> keys(u)
KeySet for a JSON3.Object{Base.CodeUnits{UInt8, String}, Vector{UInt64}} with 2 entries. Keys:
:struct1
:struct2
Than each element can be read as a separate Dict (here I cast it to Dict for readibility):
julia> Dict(u[:struct2])
Dict{Symbol, Any} with 1 entry:
:arg1 => 346.4
julia> Dict(u[:struct1])
Dict{Symbol, Any} with 2 entries:
:arg1 => 2.1865e5
:arg2 => 90
Now suppose you have a dedicated Julia struct to fill-in with those values such as:
Base.#kwdef struct MyStruct
arg1::Float64 = 0.0
arg2::Int = 0
end
If you now want to store your JSON in such struct you can do:
julia> [MyStruct(;u[key]...) for key in keys(u)]
2-element Vector{MyStruct}:
MyStruct(218650.27, 90)
MyStruct(346.4, 0)

json: cannot unmarshal number into Go value of type map[string]interface {}

terraform apply throws error:
Error: json: cannot unmarshal number into Go value of type map[string]interface {}
on main.tf line 145, in data "aws_lambda_invocation" "update-user-pool-invocation":
145: data "aws_lambda_invocation" "update-user-pool-invocation" {
The code, according to the doc:
data "aws_lambda_invocation" "update-user-pool-invocation" { # line 145 is this one
function_name = module.update-user-pool.function_name
input = <<JSON
{
"Name": "Invocation"
}
JSON
}
What number it cannot unmarshal? There are no numbers. I tried:
replace input section with input = {} because I don't really need it
write input as input = "{ \"Name\": \"Invocation\" }"
copy&paste input from the doc
How to fix it?