[javascript] object, string, yaml, buffer 변환하기
in Javascript on Javascript
Object 를 string, yaml, buffer 로 변환하기
Object <-> String
const obj = {
id: 'stove99',
rel: {
friends: ['hd', 'er']
}
};
// object <-> string
const json_str = JSON.stringify(obj);
console.log(json_str); // {"id":"stove99","rel":{"friends":["hd","er"]}}
console.log(JSON.parse(json_str)); // { id: 'stove99', rel: { friends: [ 'hd', 'er' ] } }
Object <-> Buffer
npm i bson
# 또는
yarn add bson
import * as bson from 'bson';
const obj = {
id: 'stove99',
rel: {
friends: ['hd', 'er']
}
};
const buf = bson.serialize(obj);
console.log(buf); // <Buffer 41 00 00 00 02 69 64 00 08 ....>
console.log(bson.deserialize(buf)); // { id: 'stove99', rel: { friends: [ 'hd', 'er' ] } }
Object <-> yaml
npm i yaml
# 또는
yarn add yaml
import * as yaml from 'yaml';
const obj = {
id: 'stove99',
rel: {
friends: ['hd', 'er']
}
};
const yaml_str = yaml.stringify(obj);
/*
id: stove99
rel:
friends:
- hd
- er
*/
console.log(yaml_str);
console.log(yaml.parse(yaml_str)); // { id: 'stove99', rel: { friends: [ 'hd', 'er' ] } }