Parsing a valid json string by serde will cause an error - "trailing characters"

502 Views Asked by At

I have a Rust library and Ruby project. I call a Rust function from Ruby via FFi.

There's a function in the Rust library that receives a string and converts it into json.

Ruby side:

my_json_raw_str = {
  network: {
    server_address: "my_server.com"
  }
}

res = send_it_to_rust(my_json_raw_str.to_json)

A function in Rust will throw an exception when parsing json string sent to it from Ruby.

An error returned from Rust:

Invalid parameters: trailing characters at line 1 column 47\nparams: [{\"network\":{\"server_address\":\"my_server.com\"}}\u0000]

Json is valid, isn't it?

serde, serde_json and serde_derive are used on Rust side.

How to fix the error and why is it caused?

1

There are 1 best solutions below

0
On BEST ANSWER

Json is valid, isn't it?

Your JSON is not valid, because your FFI layer is not correct: if you look at the error it's clearly telling you that there is a trailing NUL byte in your data, meaning when bridging between C and Rust you left the trailing NUL byte from the C string.