How to convert mongodb document to JSON string? - mongodb

I am using mongodb rust driver, But I don't know how to convert mongodb::bson::Document to JSON format.
let document: mongodb::bson::Document = client
.database("demo")
.collection("folder")
.find_one(doc!{})
.await?
.unwrap();
println("{:?}", document); // How to convert `document` to json string?
I want to send this JSON string from server as response.

mongodb::bson::Document implements Serialize from serde, so you can use serde_json::to_string, or other functions from serde_json to serialize the data to JSON.

Related

Decode Arbitrary JSON in Swift

I am trying decode a JSON with below structure and convert to a Swift struct object.
"{\"createdAt\":\"2021-07-20T06:53:05.755Z\",\"extraPayload\":\"32bd7d6691964519\",\"messageID\":\"a5f77d0a27da2e14a78ce4d736590bb3c369d5e5bebd36339553e3b699b82d13\",\"publishedAt\":\"2021-07-20T06:53:05.836655Z\"}"
Both the publishedAt and messageID fields are fixed and any other fields in the JSON can be arbitrary based on a particular use-case.
In this case both fields createdAt and extraPayload are completely optional and another case it could be something like appConfig:true etc apart from the 2 fixed fields.
How can I map into a struct with below format which has 2 mandatory fixed fields and arbitrary part captured using a Dictionary of type [String:Any]?
public struct MessagePayload {
/**
* Message identifier — opaque non-empty string.
*/
let messageID: String
/**
* ISO 8601 date indicating a moment when the message was published to the ACN back-end service.
*/
let publishedAt: String
/**
* Application-specific fields.
*/
let messageObject: [String:Any]?
}
I have tried using Swift Codable but it does not support [String:Any].
It seems like JSONSerialization from Foundation is probably a better fit for your use case. This will decode the JSON data directly into an Any type, which you can then cast to [String: Any] to access the underlying properties.
let decoded = try? JSONSerialization.jsonObject(with: myJsonData, options: []) as? [String: Any]
decoded?["messageID"]
decoded?["publishedAt"]
// ...access other properties as needed

Jolt: Json string literal to json object

I am looking for the way to transform JSON string to Json object.
I have a Json
input:
{
"item":"{\"currency\":\"USD\",\"content\":\"12\" TV\"}"
}
Is there a way to transform the string to json object using Jolt?
expected output:
{
"item":{"currency":"USD","content":"12\" TV"}
}
Thanks
David

Convert date format from json data in the model and then pass to controller

Here in my model I have a few struct to handle the data from server
struct Articles: Decodable {
var content : [ArticleData]
}
struct ArticleData: Decodable {
var title: String
var date_time: Date
var image: String
}
From the jason, I get a date, it's like that:
"date_time": 1524842056.035,
First question:
I set the type of this type in model Date as you see in ArticleData, it that correct?
Then I read this json in the model something like that:
guard let json = try? JSONDecoder().decode(Articles.self, from: data!) else {
completion(.failure(loginError.networkError))
return
}
completion(.success(json.content))
As you can see, I get an array from server json.content that contain title, date_time and image. I want to convert it here in the model and pass everything in completion to the controller.
could you help me on that?
Thanks :)
you can use type 'String' for your date and then convert it using dateFormatter or, use 'dateDecodingStrategy' function in your decoder.
for passing the data you are already doing the correct thing. where ever you call the method you can get the model.

How do I convert Postgres dates to ISO8601 in JSON responses with Vapor 3 running on Heroku?

I have a Vapor 3 API up on Heroku. Unfortunately, it's not handling dates correctly. Originally, I thought I could just treat dates like strings for simplicity in Vapor, like so:
struct MyModel {
var time: String?
}
But whenever I fetch MyModels from the db and return it, the time key doesn't appear at all (while other keys and values have no problems). I thought I might be able to just change time's type to Date, but that resulted in the same thing, and I've already used ContentConfig to set the JsonEncoder.dateEncodingStrategy to .iso8601 (again, no luck – perhaps because dateEncodingStrategy only supports millis on Linux, which is what Heroku uses?).
How do I convert Postgres dates to ISO8601 in json with Vapor 3 running on Heroku?
Got it working! Just changed the properties to Dates, and manually converted request query parameters to Dates as well (for use in filter calls). So, a little more by hand than most things in Vapor 3, but not terrible.
Eg my model looks like this now:
struct MyModel {
var time: Date?
}
And then when I try to filter by date I do something like this:
var builder = MyModel.query(on: req)
if let afterString: String = try? self.query.get(String.self, at: "after") {
let afterDate: Date? = DateFormatter.iso8601Full.date(from: afterString)
builder = builder.filter(\.time > afterDate)
}
where after is a url parameter, and DateFormatter.iso8601Full is my iso8601 date formatter. Then when I'm returning an array of MyModels in a response, I map the array to an array of MyModelResponseObjects which look like this:
struct MyModelResponseObject {
var time: String?
}
by doing something like this:
myModelsFuture.all().map(to: [MyModelResponseObject].self, { (myModels) -> [MyModelResponseObject] in
return myModels.map { it in
return MyModelResponseObject(time: DateFormatter.iso8601Full.string(from: it.time ?? Date.init(timeIntervalSince1970: 0)))
}
}
So basically I'm manually converting the dates into the format that I want when returning them in JSON.

How to parse Firestore FieldValue to Date in Swift

I am storing a document within a collection in a Cloud Firestore database. In this document, I want a reference to when the document was stored so I am using Firestore's FieldValue object which has a serverTimeStamp() function.
I am unable to parse this FieldValue object on the client as either a Date/NSDate or String. I have spent some time reading the Firestore iOS documentation and cannot find any leads on this.
There is no issue getting the FieldValue from the database to the client, however, I am unable to cast/convert the timeStamp of type FieldValue to anything.
Attempts to convert to string and date:
let timeStampString : String = message.timeStamp
let timeStampDate = Date(timeIntervalSince1970: message.timeStamp)
Cannot assign value of type FieldValue to type String
Cannot convert value of type FieldValue to expected argument type TimeInterval (aka Double)
Edit: After reviewing Doug Stevenson's answer, the best way to handle this is by casting your timeStamp value to a TimeStamp (not FieldValue) when reading the info on the client.
let timeStamp = document["yourTimeStampKey"] as! TimeStamp
rather than
let timeStamp = document["yourTimeStampKey"] as! FieldValue
There's no parsing needed. Firestore timestamp fields are of type Timestamp, which you should use directly. It represents a point in time with nanosecond precision.
Code:
let timeStamp = document["yourTimeStampKey"] as! TimeStamp
rather than
let timeStamp = document["yourTimeStampKey"] as! FieldValue