JSON / YAML

Лекция 15

JSON

JSON

  • JavaScript Object Notation
  • текстовый формат основанный на js
  • но, независимый от него
  • легко читается
  • лаконичный
  • передача данных между приложениями
  • объект или массив
  • .json

JSON - Object

JSON - Array

JSON - Value

JSON - String

JSON - Number

JSON


{
  "firstname": "Jack",
  "lastname": "Shepard"
}
    

JSON


[
  { "name": "Jack" },
  { "name": "Jonh" },
  { "name": "Hugo" }
]
    

JSON


{
 "firstName": "Jack",
 "lastName": "Shepard",
 "address": {
   "street": "Westside",
   "city": "Los Angeles",
   "postalCode": 101101
 },
 "phoneNumbers": [
   "812 123-1234",
   "916 123-4567"
 ]
}
    

JSON



  Jack
  Shepard
  
Westside Los Angeles 101101
812 123-1234 916 123-4567

JSON


JSON.stringify(value[, replacer[, space]])

// value - значение для преобразования

// replacer - функция или массив
// для преобразования или выборки

// space - отступы для форматирования
    

JSON


JSON.stringify({});
// '{}'

JSON.stringify(true);
// 'true'

JSON.stringify('foo');
// '"foo"'

JSON.stringify([1, 'false', false]);
// '[1,"false",false]'

JSON.stringify({ x: 5 });
// '{"x":5}'
    

JSON


JSON.stringify({ a: 2 }, null, ' ');
// {
//  "a": 2
// }
    

JSON


JSON.stringify({ a: 2, b: { c: 3 } }, null, 4);
// {
//     "a": 2,
//     "b": {
//         "c": 3
//     }
// }
    

JSON


const obj = {
  foo: 'foo',
  toJSON: function() {
    return 'bar';
  }
};

JSON.stringify(obj);        // '"bar"'
JSON.stringify({ x: obj }); // '{"x":"bar"}'
    

JSON


const foo = {
  foundation: 'Mozilla', model: 'box',
  week: 45, transport: 'car', month: 7
};

JSON.stringify(foo, function(key, value) {
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
});

JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}'
    

JSON


JSON.parse(text[, reviver])

// text - строка для разбора
// reviver - функция для преобразования
    

JSON


JSON.parse('{}');
// {}

JSON.parse('true');
// true

JSON.parse('"foo"');
// "foo"

JSON.parse('[1, 5, "false"]');
// [1, 5, "false"]

JSON.parse('null');
// null
    

JSON


JSON.parse('{"p": 5}', function(k, v) {
  if (k === '') { return v; }
  return v * 2;
});
// { p: 10 }
    

YAML

YAML

  • YAML Ain't Markup Language
  • Yet Another Markup Language
  • ориентированный на данные
  • еще более человекочитаемый
  • еще более лаконичный
  • поддерживает ссылки, комментарии, типы
  • .yml или .yaml
  • yaml.org

YAML


firstname: Jack
lastname: Shepard

address:
  street: Westside
  city: Los Angeles
  postalCode: 101101

phoneNumbers:
- 812 123-1234
- 916 123-4567
    

YAML


- Mark McGwire
- Sammy Sosa
- Ken Griffey
    

[
  "Mark McGwire",
  "Sammy Sosa",
  "Ken Griffey"
]
    

YAML


hr:  65    # Home runs
avg: 0.278 # Batting average
rbi: 147   # Runs Batted In
    

{
  "hr": 65,
  "avg": 0.278,
  "rbi": 147
}
    

YAML


american:
  - Boston Red Sox
  - Detroit Tigers
  - New York Yankees
national:
  - New York Mets
  - Chicago Cubs
  - Atlanta Braves
    

{ "american": ["Boston Red Sox","Detroit Tigers",
    "New York Yankees"],
  "national": ["New York Mets","Chicago Cubs",
    "Atlanta Braves"]
}
    

YAML


- [name, hr, avg]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa, 63, 0.288]
    

[
  [ "name", "hr", "avg" ],
  [ "Mark McGwire", 65, 0.278 ],
  [ "Sammy Sosa", 63, 0.288 ]
]
    

YAML


Mark McGwire: { hr: 65, avg: 0.278 }
Sammy Sosa: { hr: 63, avg: 0.288 }
    

{
  "Mark McGwire": {
    "hr": 65,
    "avg": 0.278
  },
  "Sammy Sosa": {
    "hr": 63,
    "avg": 0.288
  }
}
    

YAML


- item    : Super Hoop
  quantity: 1
- item    : Basketball
  quantity: 4
- item    : Big Shoes
  quantity: 1
    

[
  { "item": "Super Hoop", "quantity": 1 },
  { "item": "Basketball", "quantity": 4 },
  { "item": "Big Shoes", "quantity": 1 }
]
    

YAML


- step:  &id001
  instrument: Lasik 2000
  pulseEnergy: 5.4
  pulseDuration: 12
- step: *id001
    

[{ "step": { "pulseEnergy": 5.4,
      "instrument": "Lasik 2000",
      "pulseDuration": 12}
  },
  { "step": { "pulseEnergy": 5.4,
      "instrument": "Lasik 2000",
      "pulseDuration": 12}
  }]
    

YAML

YAML


http://www.yaml.org/spec/1.2/spec.html
    

http://yaml-online-parser.appspot.com
    

YAML


npm install yamljs
    

YAML


YAML = require('yamljs');

// parse YAML string
nativeObject = YAML.parse(yamlString);

// Generate YAML
yamlString = YAML.stringify(nativeObject, 4);

// Load yaml file using YAML.load
nativeObject = YAML.load('myfile.yml');
    

YAML - Langs case


# COMMON
created-at: Created At
updated-at: Updated At
actions: Actions
list: List
view: View
new: New
edit: Edit
save: Save
delete: Delete
    

YAML - Langs case


# COMMON
created-at: Créé à
updated-at: Mise à jour à
actions: Actions
list: Liste
view: Vue
new: Nouveau
edit: Modifier
save: Enregistrer
delete: Supprimer
    

YAML - Langs case


const langsTransform
  = rootRequire('utils/langsTransform');

app.use('/langs/:lang.json', langsTransform);
    

YAML - Langs case


let yaml = require('yamljs');
let cache = {};

module.exports = (request, response, next) => {
  if (!request.params.lang) next();

  try {
    ...
  }
  catch(e) {
    next();
  }
};
    

YAML - Langs case


let cached = cache[request.params.lang];

if (cached) {
  response.json(cached);
  return;
}

let lang = yaml.load(`${__rootdir}/public
  /langs/${request.params.lang}.yaml`);

cache[request.params.lang] = lang;
response.json(lang);