Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go 드라이버
/

문서 데이터 형식: 확장 JSON

JSON 객체, 배열, 숫자, 문자열, 부울 및 null 값을 나타내는 데이터 형식입니다. 확장 JSON 형식은 $ 문자가 접두사로 붙은 예약된 키 설정하다 정의하여 MongoDB 데이터를 저장 데 사용하는 형식인 BSON 의 각 유형에 직접적으로 대응하는 필드 유형 정보를 나타냅니다.

MongoDB 확장 JSON BSON 데이터를 나타내는 다양한 문자열 형식을 제공합니다. 각 형식은 JSON RFC 를 준수하며 특정 사용 사례를 충족합니다.

표준 형식이라고도 하는 확장 형식은 정보 손실 없는 양방향 변환을 위해 모든 BSON 유형에 대한 특정 표현을 제공합니다. Relaxed 형식은 더 간결하고 일반 JSON 에 가깝지만 숫자 필드의 특정 바이트 크기와 같은 모든 유형 정보를 나타내지는 않습니다.

다음 표에는 JSON 형식에 대한 설명이 나와 있습니다.

이름
설명

확장

Also known as the canonical format, this JSON representation avoids loss of BSON type information.
This format prioritizes type preservation at the loss of human-readability and interoperability with older formats.

완화 모드

JSON representation that describes BSON documents with some type information loss.
This format prioritizes human-readability and interoperability at the loss of certain type information.

Shell

JSON representation that matches the syntax used in the MongoDB shell.
This format prioritizes compatibility with the MongoDB shell, which often uses JavaScript functions to represent types.

엄격한

Deprecated This representation is the legacy format that fully conforms to the JSON RFC and allows any JSON parser to read the type information.

JSON, BSON 및 확장 JSON에 대해 자세히 학습하려면 MongoDB Server 매뉴얼의 JSON 및 BSON에 대한 문서확장 JSON 참조를 참조하세요.

다음 탭은 각 확장 JSON 형식으로 표시되는 ObjectId, 날짜 및 긴 숫자 필드 포함된 문서 보여줍니다. 탭에서 선택하여 각 JSON 형식으로 표시된 동일한 데이터를 확인합니다.

{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": { "$numberLong": "1601499609" }},
"numViews": { "$numberLong": "36520312" }
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": "2020-09-30T18:22:51.648Z" },
"numViews": 36520312
}
{
"_id": ObjectId("573a1391f29313caabcd9637"),
"createdAt": ISODate("2020-09-30T18:22:51.648Z"),
"numViews": NumberLong("36520312")
}
{
"_id": { "$oid": "573a1391f29313caabcd9637" },
"createdAt": { "$date": 1601499609 },
"numViews": { "$numberLong": "36520312" }
}

bson.UnmarshalExtJSON() 메서드를 호출하여 확장 JSON 문자열을 ​ 구조체로 읽을 수 있습니다. 이 메서드는 확장 JSON 문자열을 구문 분석하고 결과를 지정된 값 매개변수에 저장합니다.

이 예시 확장 JSON 문자열을 다음 Person 구조체로 읽는 방법을 보여줍니다.

type Person struct {
ID bson.ObjectID `bson:"_id"`
Name string
Age int
Birthday bson.DateTime
Address Address
Hobbies []string
}
type Address struct {
Street string
City string
State string
}

다음 코드는 UnmarshalExtJSON() 메서드를 사용하여 확장 JSON 문자열을 읽고 데이터를 Person 인스턴스 로 언마셜링합니다.

var extJsonString = "{\"_id\":{\"$oid\":\"578f6fa2df35c7fbdbaed8c5\"},\"name\":\"Liana Ruiz\",\"age\":46,\"birthday\":{\"$date\":\"1988-01-15T00:00:00Z\"},\"address\":{\"street\":\"500 Slippery Rock Road\",\"city\":\"Round Rock\",\"state\":\"AR\"},\"hobbies\":[\"cycling\", \"baking\"]}"
var p Person
err := bson.UnmarshalExtJSON([]byte(extJsonString), false, &p)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Go Struct Representation:\n%+v\n", p)
Go Struct Representation:
{ID:ObjectID("578f6fa2df35c7fbdbaed8c5") Name:Liana Ruiz Age:46 Birthday:569203200000 Address:{Street:500 Slippery Rock Road City:Round Rock State:AR} Hobbies:[cycling baking]}

bson.MarshalExtJSON() 메서드를 호출하여 ​ 구조체 또는 BSON 문서 의 인스턴스 에서 확장 JSON 문자열을 생성할 수 있습니다. 다음 예시 에서는 구조체 또는 BSON 문서 에서 Relaxed 형식의 확장 JSON 문자열을 생성합니다. Struct 또는 bson.D 탭 선택하여 해당 예시 확인합니다.

var person = Person{
ID: bson.NewObjectID(),
Name: "Matteo Carisi",
Age: 49,
Birthday: bson.NewDateTimeFromTime(time.Date(1975, 10, 30, 0, 0, 0, 0, time.UTC)),
Address: Address{Street: "14a Corner Court", City: "Springfield", State: "IL"},
Hobbies: []string{"cooking", "birdwatching"},
}
newExtJsonStringFromStruct, err := bson.MarshalExtJSON(person, false, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromStruct)
Extended JSON Representation:
{"_id":{"$oid":"686688fa7c1a2e75405f4697"},"name":"Matteo Carisi","age":49,"birthday":{"$date":"1975-10-30T00:00:00Z"},"address":{"street":"14a Corner Court","city":"Springfield","state":"IL"},"hobbies":["cooking","birdwatching"]}
bsonDocument := bson.D{{"hello", "world"}, {"number", 1}}
newExtJsonStringFromBson, err := bson.MarshalExtJSON(bsonDocument, false, true)
if err != nil {
panic(err)
}
fmt.Printf("Extended JSON Representation:\n%s\n", newExtJsonStringFromBson)
Extended JSON Representation:
{"hello":"world","number":1}

MarshalExtJSON() 의 두 번째 매개변수는 출력 문자열이 표준(확장) 형식인지 또는 완화 형식인지를 결정합니다. 앞의 예시 에서는 falsecanonical 매개 변수로 전달하므로 출력은 Relaxed JSON 입니다.

참고

에포크 시간 이전 날짜

1월 1, 1970, 00:00:00 UTC(에포크 시간) 이전의 날짜 값을 마셜링하면 해당 값은 Relaxed JSON 에서 Unix 타임스탬프로 표시됩니다. 날짜가 에포크 시간 이후인 경우 읽을 수 있는 날짜 형식으로 표시됩니다.

bson.MarshalExtJSONIndent() 메서드를 사용하여 줄 바꿈, 접두사 및 들여쓰기를 포함하는 형식이 지정된 확장 JSON 문자열을 인쇄할 수 있습니다.

다음 코드는 MarshalExtJSONIndent() 메서드를 사용하여 두 개의 들여쓰기로 서식이 지정된 이전 예시 의 JSON 문자열을 출력합니다.

formattedString, err := bson.MarshalExtJSONIndent(person, false, true, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", formattedString)
{
"_id": {
"$oid": "686688fa7c1a2e75405f4697"
},
"name": "Matteo Carisi",
"age": 49,
"birthday": {
"$date": "1975-10-30T00:00:00Z"
},
"address": {
"street": "14a Corner Court",
"city": "Springfield",
"state": "IL"
},
"hobbies": [
"cooking",
"birdwatching"
]
}

이 가이드에 사용된 메서드 및 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

BSON

이 페이지의 내용