Convert JSON to YAML with npm module (CLI)

Convert JSON to YAML with npm module (CLI)

Convert JSON to YAML (json2yaml)

Install the json2yaml module to convert JSON to YAML.

$ npm install json2yaml

Sample JSON file.

sample.json

{
  "data": {
    "type": "array",
    "id": {
      "type": "integer"
    },
    "message": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "message"
  ]
}

Change sample.json to yaml format.

$ npx json2yaml sample.json
---
  data:
    type: "array"
    id:
      type: "integer"
    message:
      type: "string"
  required:
    - "id"
    - "message"

If you want to redirect to a file, use > as follows

$ npx json2yaml sample.json > out.yaml

JSONをYAMLに変換する(js-yaml)

Install the js-yaml module to convert JSON to YAML.

$ npm install js-yaml

Convert YAML to JSON.

$ npx js-yaml sample.json
data:
  type: array
  id:
    type: integer
  message:
    type: string
required:
  - id
  - message

js-yaml produces cleaner output.

Also, js-yaml will convert to JSON format if the argument is a yml file.

$ npx js-yaml sample.yml
{
  "data": {
    "type": "array",
    "id": {
      "type": "integer"
    },
    "message": {
      "type": "string"
    }
  },
  "required": [
    "id",
    "message"
  ]
}

コメント

タイトルとURLをコピーしました