Coder Social home page Coder Social logo

ionicabizau / json2md Goto Github PK

View Code? Open in Web Editor NEW
544.0 13.0 79.0 185 KB

:pushpin: A JSON to Markdown converter.

Home Page: http://ionicabizau.net/blog/27-how-to-convert-json-to-markdown-using-json2md

License: MIT License

JavaScript 100.00%
hacktoberfest

json2md's Introduction

json2md

json2md

Support me on Patreon Buy me a book PayPal Ask me anything Version Downloads Get help on Codementor

Buy Me A Coffee

A JSON to Markdown converter.

If you're looking to use this on the client side, that's also possible. Check out the dist directory.

โ˜๏ธ Installation

# Using npm
npm install --save json2md

# Using yarn
yarn add json2md

๐Ÿ“‹ Example

const json2md = require("json2md")

console.log(json2md([
    { h1: "JSON To Markdown" }
  , { blockquote: "A JSON to Markdown converter." }
  , { img: [
        { title: "Some image", source: "https://example.com/some-image.png" }
      , { title: "Another image", source: "https://example.com/some-image1.png" }
      , { title: "Yet another image", source: "https://example.com/some-image2.png" }
      ]
    }
  , { h2: "Features" }
  , { ul: [
        "Easy to use"
      , "You can programmatically generate Markdown content"
      , "..."
      ]
    }
  , { h2: "How to contribute" }
  , { ol: [
        "Fork the project"
      , "Create your branch"
      , "Raise a pull request"
      ]
    }
  , { h2: "Code blocks" }
  , { p: "Below you can see a code block example." }
  , { "code": {
        language: "js"
      , content: [
          "function sum (a, b) {"
        , "   return a + b"
        , "}"
        , "sum(1, 2)"
        ]
      }
    }
]))
// =>
// # JSON To Markdown
// > A JSON to Markdown converter.
//
// ![Some image](https://example.com/some-image.png)
//
// ![Another image](https://example.com/some-image1.png)
//
// ![Yet another image](https://example.com/some-image2.png)
//
// ## Features
//
//  - Easy to use
//  - You can programmatically generate Markdown content
//  - ...
//
// ## How to contribute
//
//  1. Fork the project
//  2. Create your branch
//  3. Raise a pull request
//
// ## Code blocks
//
// Below you can see a code block example.
//
// ```js
// function sum (a, b) {
//    return a + b
// }
// sum(1, 2)
// ```

โ“ Get Help

There are few ways to get help:

  1. Please post questions on Stack Overflow. You can open issues with questions, as long you add a link to your Stack Overflow question.
  2. For bug reports and feature requests, open issues. ๐Ÿ›
  3. For direct and quick help, you can use Codementor. ๐Ÿš€

๐Ÿ“ Documentation

json2md(data, prefix)

Converts a JSON input to markdown.

Supported elements

Type Element Data Example
h1 Heading 1 The heading text as string. { h1: "heading 1" }
h2 Heading 2 The heading text as string. { h2: "heading 2" }
h3 Heading 3 The heading text as string. { h3: "heading 3" }
h4 Heading 4 The heading text as string. { h4: "heading 4" }
h5 Heading 5 The heading text as string. { h5: "heading 5" }
h6 Heading 6 The heading text as string. { h6: "heading 6" }
p Paragraphs The paragraph text as string or array (multiple paragraphs). { p: "Hello World"} or multiple paragraphs: { p: ["Hello", "World"] }
blockquote Blockquote The blockquote as string or array (multiple blockquotes) { blockquote: "Hello World"} or multiple blockquotes: { blockquote: ["Hello", "World"] }
img Image An object or an array of objects containing the title, source and alt fields. { img: { title: "My image title", source: "http://example.com/image.png", alt: "My image alt" } }
ul Unordered list An array of strings or lists representing the items. { ul: ["item 1", "item 2"] }
ol Ordered list An array of strings or lists representing the items. { ol: ["item 1", "item 2"] }
hr Separator None { hr: "" }
code Code block element An object containing the language (String) and content (Array or String) fields. { code: { "language": "html", "content": "<script src='dummy.js'></script>" } }
table Table An object containing the headers (Array of Strings) and rows (Array of Arrays or Objects). { table: { headers: ["a", "b"], rows: [{ a: "col1", b: "col2" }] } } or { table: { headers: ["a", "b"], rows: [["col1", "col2"]] } }
link Link An object containing the title and the source fields. { title: 'hello', source: 'https://ionicabizau.net' }

You can extend the json2md.converters object to support your custom types.

json2md.converters.sayHello = function (input, json2md) {
   return "Hello " + input + "!"
}

Then you can use it:

json2md({ sayHello: "World" })
// => "Hello World!"

Params

  • Array|Object|String data: The input JSON data.
  • String prefix: A snippet to add before each line.

Return

  • String The generated markdown result.

async

Params

  • Array|Object|String data: The input JSON data.
  • String prefix: A snippet to add before each line.

Return

  • Promise.<String, Error> The generated markdown result.

๐Ÿ˜‹ How to contribute

Have an idea? Found a bug? See how to contribute.

๐Ÿ’– Support my projects

I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously, this takes time. You can integrate and use these projects in your applications for free! You can even change the source code and redistribute (even resell it).

However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:

  • Starring and sharing the projects you like ๐Ÿš€

  • Buy me a bookโ€”I love books! I will remember you after years if you buy me one. ๐Ÿ˜ ๐Ÿ“–

  • PayPalโ€”You can make one-time donations via PayPal. I'll probably buy a coffee tea. ๐Ÿต

  • Support me on Patreonโ€”Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).

  • Bitcoinโ€”You can send me bitcoins at this address (or scanning the code below): 1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6

Thanks! โค๏ธ

๐Ÿ’ซ Where is this library used?

If you are using this library in one of your projects, add it in this list. โœจ

  • @lm_fe/scripts
  • @eventcatalog/utils
  • @servable/manifest
  • @best/github-integration
  • @microfleet/schema2md
  • @cypress/schema-tools
  • @asyncapi/diff
  • @sidneys/releasenotes
  • merak-compile
  • @best/store
  • jumia-travel-changelog
  • npm-ex-xpi
  • doc-vue3
  • @feizheng/react-markdown-props
  • heat-sfdx-tooling
  • @cobalt-engine/change-logger
  • lambda-docs-2md
  • servable-manifest
  • @gracexwho/model-card-generator
  • rap2doc
  • @dschau/gatsby-source-google-docs
  • rush-archive-project-plugin
  • sfhdown
  • tcdown
  • bookmark2md
  • cwq
  • @bonitasoft/dependency-list-to-markdown
  • github-repo-tools
  • gridsome-source-google-docs
  • notion2mdblog
  • kindle-highlights
  • make-postgres-markdown
  • @dlsl/hardhat-markup
  • @aligov/module-doc
  • @opas/plugin-doc
  • @xygengcn/koa-api-docs
  • @dididc/dc-extension
  • parse-google-docs-json
  • cli-demo3
  • gatsby-source-gdocs2md
  • kbase-components
  • lbdoc-p
  • chdown-workers
  • @bwagener/gridsome-source-google-docs
  • doc-cli
  • galaxy-vuepress-docs
  • dargstack_rgen
  • react-docgen-markdown
  • @e2y/bdd-dictionary-generator
  • @medyll/css-fabric-helper
  • @oasis-engine/oasis-run
  • @flive/react-kit
  • @shelex/schema-tools
  • @apica-io/asm-auto-deploy
  • @haimmag/schema-tools
  • rober19-config
  • @klarna/postgres-to-docs
  • @wii/swagger-plugin-transform-doc
  • cloudcastsdown
  • eddown
  • msdown
  • laradown
  • my_ccdown
  • mokker
  • gatsby-source-google-docs
  • gatsby-source-google-docs-sheets
  • platzi-virtual-machine
  • chdown
  • @yesand/asterism
  • ccdown
  • doc-vue
  • @hitorisensei/monorepo-readme-generator
  • uxcore-tools
  • @gigsboat/cli
  • joi-md-doc
  • @everything-registry/sub-chunk-1986
  • describe-dependencies
  • lab-changelog
  • node-red-contrib-json2md
  • p2doc
  • @eventcatalogtest/plugin-doc-generator-asyncapi
  • @solarity/hardhat-markup
  • @s-ui/changelog
  • component-docs-2md
  • codexer
  • @balmacefa/function_tool_kit
  • dokuinjs
  • @mjefi/instags
  • machine-ip
  • flawed-code-scanner
  • pantheon_site_management
  • postgres-markdown
  • reposier
  • gatsby-source-google-docs-team
  • work-webpack
  • vue-md-gen
  • @hitorisensei/markdown-readme-generator
  • @jswork/react-markdown-props
  • terraform2md
  • solidity-benchmark
  • utterance-to-markdown
  • @eventcatalog/plugin-doc-generator-asyncapi
  • type-graphql-to-md
  • @cloudcatalog/cli
  • @cloudcatalog/cli-testI am using this library to generate documentation for my projects, being integrated with blah.

๐Ÿ“œ License

MIT ยฉ Ionicฤƒ Bizฤƒu

json2md's People

Contributors

adoyle-h avatar cedricdelpoux avatar danielbastos11 avatar dependabot[bot] avatar ionicabizau avatar ivanwei avatar janinawibker avatar johnbeech avatar jpoehnelt avatar justinsunho avatar keithhchen avatar macno avatar mitogh avatar oahehc avatar reklatsmasters avatar reymon359 avatar roiros avatar shuxiaotai avatar steghoja avatar tteltrab avatar younho9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json2md's Issues

Images title are transformed to alt

json2md({
  img: {
    source: "source",
    title: "title"
  }
}

is transformed to ![title](source) instead of ![](source "title").

In markdown [] is used for alt attrs

JS helper libraries / functions

Are there any JS client libraries or helper functions available for generation of the json objects that are needed to be created to inject into the array supplied to the json2md function?

I'm looking to create some helper functions like

  • getHeader(level, text)
  • getParagraph(text)
  • getCodeBlock(code, language, content)

I'd imagine some of these types of functions were already implemented elsewhere by the projects that consume this library.

Are there patterns for these helper type functions being established somewhere or tracked alongside this repo?

get a table in the browser

Hello,
Using json2md.min.js in the browser I get a problem with

var table3 = json2md({"table":{"header":["Petal.Length","Petal.Width","Species"],"rows":[{"Petal.Length":1.4,"Petal.Width":0.2,"Species":"setosa"},{"Petal.Length":1.4,"Petal.Width":0.2,"Species":"setosa"},{"Petal.Length":1.3,"Petal.Width":0.2,"Species":"setosa"}]}});

This returns the error: There is no such converter: table.

Double empty lines between headers and list

When setting a list just after a header, there are two empty lines between them, separating them too much, when there should be just a single one. Seems it's due to the fact headers add an newline after them and lists add a newline before them, so when joining the fragments this result in three consecutive newlines. I think it would be better no block add a newline before or after them, and instead the joining add the two ones to create the empty line. This failing test checks it:

    test.it("should add a single newline between headers and ordered lists", function(cb) {
        test.expect(json2md([
            {
                h1: "Heading 1"
            },
            {
                ol: [
                    "item 1", "item 2"
                ]
            }
        ])).toBe("# Heading 1\n\n 1. item 1\n 2. item 2\n");
        cb();
    });

Images in lists

To convert a list with image, I need to put the raw Markdown in the list item:

{ ul: [ 
     '![](url "title") bullet 1',
     'bullet 2',
     'bullet 3' ]
 }

It would be better to have the json image syntax:

{ ul: [ 
     [{img: {source: url, title: "title"}}, "bullet 1],
     'bullet 2',
     'bullet 3' ]
 }

Nesting

Does this lib do nesting? If not, maybe something like this would work?

{ h2:  
  {
    a: {
      href: 'google.com',
      child: 'hello world'
    }
  }
}

// produces
// ## [Hello World](google.com)

{ h2:  
  {
    a: {
      href: 'google.com',
      child: {
        p: 'hello world'
      }
    }
  }
}

can I use several custom converters?

Hi,
I could use both custom converters but not together, but only one or the other:
const conv = json2md.converters
conv.section = function (input, json2md) { return "####-section " + input }
conv.title = function (input, json2md) { return "##-title " + input }

But if I use them together, json2md dies quietly and there is no result at all. How - and is it possible - to use several converters?

a conversion fails on table data

data = input.rows.map(function (r) {
return " | " + (Array.isArray(r) ? r.map(function (el) {
return parseTextFormat(json2md(el));
}).join(" | "): input.headers.map(function (h) {
return parseTextFormat(json2md(r[h]));
}).join(" | "))+ " | ";
}).join("\n") + " | ";

ๆ‚จๅฅฝ๏ผš
ๆˆ‘ๅœจ่ฝฌๆข่กจๆ ผๆ•ฐๆฎ็š„ๆ—ถๅ€™๏ผŒ็”จmdๆ‰“ๅผ€ๅคฑ่ดฅใ€‚ ๆŠŠ่ฟ™ๆฎตไปฃ็ ไฟฎๆ”นไบ†ไธ€ไธ‹๏ผŒๅฐฑๅฅฝไบ†ใ€‚ๅฏนๅ—๏ผŸ

JSON format

When I try to convert a valid JSON such as this:

    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}

the code throws an error saying that there is not such a converter.

Add support for emphasis formats

At the moment there is no emphasis format on the text such as bold, strong, em and italic inside of the text for instance something like:

{ p: "Below you <bold>can see a code</bold> block example." }

Should be translated into:

Below you can see a code block example.

I already implemented this on my fork, let me know if you feel is a good idea to move forward to create a a PR.

Thanks @IonicaBizau

Small issue with lists

Hey there, I'm currently trying to create output like so:

output.push({ h1: "Collection" })
categories.forEach(cat => {
  output.push({ h2: cat.name })
  cat.files.forEach(file => {
    output.push({ ul: [ {link: { title: file.name, source: file.path }}]})
  })
})

Now, that is obviously adding a ul around every link, how would I .push the opening of an ul separate from the ending so I can keep my loop?

Table values should be escaped

Having | or square brackets as table values might lead to invalid or wrong tables and should be escaped.

var json2md = require("json2md")

console.log(json2md( {
  table: { headers: ["path", "title", "text"], rows: 
  [{
    "path": "/",
    "title": "Test values with | pipe.",
    "text": "or eventually brackets too [ should be escaped ]"
}]
 } } 
))

Pretty table only works if all cells' data is String

The pretty table works great for string-only data.
However if some of my data is integer, or boolean, or something else that needs to be stringified, then the table is not prettified.

Reproduction scenario:

const rows = [
  { 'some long field name': 1000, 'another column name...': '10' },
  { 'some long field name': 2000, 'another column name...': '20' },
  { 'some long field name': 3000, 'another column name...': '30' },
];

const output = json2md({
  table: { 
    headers: ['some long field name', 'another column name...'],
    rows: rows,
    pretty: true,
  }
});

console.log(output)

The output is:

| some long field name | another column name... |โ€ˆ
| -- | ---------------------- |โ€ˆ
| 1000 | 10                     |โ€ˆ
| 2000 | 20                     |โ€ˆ
| 3000 | 30                     |โ€ˆ

If I stringify everything:

const rows = [
  { 'some long field name': '1000', 'another column name...': '10' },
  { 'some long field name': '2000', 'another column name...': '20' },
  { 'some long field name': '3000', 'another column name...': '30' },
];

then the output is as expected:

| some long field name | another column name... |โ€ˆ
| -------------------- | ---------------------- |โ€ˆ
| 1000                 | 10                     |โ€ˆ
| 2000                 | 20                     |โ€ˆ
| 3000                 | 30                     |โ€ˆ

The root of the issue is probably here: https://github.com/IonicaBizau/json2md/blob/master/lib/converters.js#L171
If the cell data is not String, e.g. number or boolean, it doesn't have length property and Math.max returns NaN. Later, the fill functions that use String.repeat will get NaN as input and therefore generate an empty string to fill the data to the left or to the right.

One way to fix it would be to have a serializers property on the input, which provides a serializer function for each header. If a serializer is not provided, then JSON.stringify could be assumed as default serializer.

There is a ใ€debuggerใ€‘ debugging statement in the npm release package ใ€json2md:2.0.1ใ€‘

Current Status

When I use the Chrome browser's ใ€F12 consoleใ€‘ to debug code, this sentence always interrupts all debugging logic repeatedly.

image

The location of the relevant code is at

debugger

Expect normal behavior of code

Only when developers need it, they self can add ใ€debuggers / BreakPointใ€‘ to relevant statements in the [Browser F12 Console].

Nested lists

Hi,

At the moment there is a problem with nested lists. The code I'm using, the intended output and the actual output are as follow:

Code:

let md = json2md({
  ol: [
    'a',
    {
      ul: [
        'I',
        'II',
        {ol: ['A', 'B']}
      ]
    },
    'b'
  ]
});

console.log(md);

Intended output:

  1. a
    • I
    • II
      1. A
      2. B
  2. b

Actual output:

  1. a

    • I
    • II
      1. A
      2. B
  2. b

--

I implemented a fix for this on my fork, but I had a problem with these lines, cause I couldn't figure out a way to only append \n on the top level list. I decided to never append \n to any list, but I guess this could be an issue somehow. Anyway, I updated the test file, hoping my solution will work fine.

Let me know what you think!

Add alignment in markdown table

I want to add some alignment features while generating markdown table whether the rows should be right, center or left.
for eg :-

  1. Alignment center
    firstname | lastname | contact
    :---: | :---: | :---:
    Nischal | Shakya | 9841890098
    Naruto | Uzumaki | 988800990
    Sasuke | Uchia | 9841145690
    Sakura | Haruna | 9849123459

  2. Alignment left
    firstname | lastname | contact
    :--- | :--- | :---
    Nischal | Shakya | 9841890098
    Naruto | Uzumaki | 988800990
    Sasuke | Uchia | 9841145690
    Sakura | Haruna | 9849123459

  3. Alignment right
    firstname | lastname | contact
    ---: | ---: | ---:
    Nischal | Shakya | 9841890098
    Naruto | Uzumaki | 988800990
    Sasuke | Uchia | 9841145690
    Sakura | Haruna | 9849123459

Match column name length and dashes

Currently table formatting looks something like this:

| name | amount | somesuperlongword | a |
| ----- | :---: | :---- | ---: |
| col1 | col2 | col3 | col4 |

It would be prettier if the output would be something along those lines:

| name | amount | somesuperlongword |    a |
| ---- | :----: | :---------------- | ---: |
| col1 | col2 | col3 | col4 |

If the column name is too short it is padded with spaces. Where those spaces are added depends on the alignment of the column.

I've already done a rough implementation of this which also addresses #49 (by adding documentation) and #60 which I could create a pull request for.

Redundant | if a table ends with \n element like link

I'm getting a redundant | pipe if the last element of the table had \n

{
  "table": {
    "headers": [
      "Col1"
    ],
    "rows": [
      {
        "Col1": {
          "link": {
            "title": "aTitle",
            "source": "http://www.example.com"
          }
        }
      }
    ]
  }
}

json2md output would be

'| Col1 |\n| ---- |\n| [aTitle](http://www.example.com)\n |\n'

Representing:

Col1
aTitle

|


If an additional column (Col2) would be added, the bug (\n in the link) would cause the value in it it to show on the next row
e.g.:

Col1 Col2
aTitle
cola

Documentation - Implementing Custom Types

Hi IonicaBizau, Great module! A really usefull tool! Thanks.

I am trying to implement a custom type and I don't think I have "registered" it properly, it doesn't seem to do the conversion I expect. Here's what the code looks like...

const json2md = require("json2md");

const URL = "https://www.youtube.com/watch?v=pBYqen3B2gc";

// add custom types for json2md
json2md.converters.linkToVideo = function(input, json2md) {
  return "Watch the video on [Youtube](" + input + ")";
};

var json = {
  h1: "",
  linkToVideo: URL,
};

console.log(json2md(json));

This outputs the h1 text but not the expected link.

# WebAssembly and the Death of JavaScript - JS Monthly - February 2018 - YouTube

My code editor tells me that converters is declared but never used, also json2md is declared but never used and it's value is never read...

So I am sure that just declaring that custom type in my code is not right... Maybe it should be part of an option object for json2md in my package.json file? Not sure how to set this up...

Can you give me a pointer?

Thanks, smerth

'link' takes 'title' and 'source', but the readme.md says differently

In the 'Readme.md' the 'link' element is defined as 'title', and 'url',
If you try this with 'url' the Link target is undefined later on.

So I took what is defined in the Tester and a 'link' with 'title' and 'source' is working fine!
Please just correct the 'Redme.md' for others getting the same Issue!

Thanks for this great implementation, it saved a lot of time already :-)

Example in README duplicates img tags

Test file:

const json2md = require("json2md")

console.log(json2md([
    { h1: "JSON To Markdown" }
  , { blockquote: "A JSON to Markdown converter." }
  , { img: [
        { title: "Some image", source: "https://example.com/some-image.png" }
      , { title: "Another image", source: "https://example.com/some-image1.png" }
      , { title: "Yet another image", source: "https://example.com/some-image2.png" }
      ]
    }
  , { h2: "Features" }
  , { ul: [
        "Easy to use"
      , "You can programmatically generate Markdown content"
      , "..."
      ]
    }
  , { h2: "How to contribute" }
  , { ol: [
        "Fork the project"
      , "Create your branch"
      , "Raise a pull request"
      ]
    }
  , { h2: "Code blocks" }
  , { p: "Below you can see a code block example." }
  , { "code": {
        language: "js"
      , content: [
          "function sum (a, b) {"
        , "   return a + b"
        , "}"
        , "sum(1, 2)"
        ]
      }
    }
]))

Actual output:

  # JSON To Markdown

  > A JSON to Markdown converter.

  ![](https://example.com/some-image.png "Some image")
  ![](https://example.com/some-image.png "Some image")

  ![](https://example.com/some-image1.png "Another image")
  ![](https://example.com/some-image1.png "Another image")

  ![](https://example.com/some-image2.png "Yet another image")
  ![](https://example.com/some-image2.png "Yet another image")


  ## Features


  - Easy to use
  - You can programmatically generate Markdown content
  - ...

  ## How to contribute


  1. Fork the project
  2. Create your branch
  3. Raise a pull request

  ## Code blocks


  Below you can see a code block example.

  ```js
  function sum (a, b) {
     return a + b
  }
  sum(1, 2)
  ```

Note the duplicated images; three in the input, three pairs, six total images in the output.

Only converting first item

I'm trying to figure out if this is an issue or simply works as designed. The example works as expected (with custom converters too):
console.log(json2md([
{ h1: "JSON To Markdown" }
, { blockquote: "A JSON to Markdown converter." }
, { img: [....
}
]))

When I send an object through with data like this example it only converts the first item it finds.
console.log(json2md([
{
h1: "I am converted",
h2: "I am not converted",
h3: "I am not converted. Sad face"
}
]))

Is that the expected behavior?

Thanks,
Kevin

Inline code support

It should be nice to support inline code:

Inline `code` has `back-ticks around` it.

Inline code has back-ticks around it.

It is in the Markdown spec.
Are you interested by a PR for this?

Rich Text and json2md args

First all, forgive me for using a single issue for two completely different problems, but I ended up mixing the two things while working on them.

Rich text

I've been working on an update to add support for Rich Text editing from JSON. I don't know if that's useful for anyone else, but it's been really handy for me. It allows for constructs like that:

  json2md({
        text: ['This is what ', {italic: {bold: 'rich'}}, ' text should ',
               'look ', {strike: {bold: 'like'}}]
      }) 

which resolves to:

This is what rich text should look like

json2md args

I was wondering if it would be a good idea to remove the _type argument and add options instead. That would allow the use of options.compact, to define whether the resulting elements should be separated by a \n, fixing the problem (check line 87 and 100 on lib/converters.js) with trailing whitespaces that I mentioned on #21 .

I put together a list of reasons to get rid of _type:

  • It would simplify the API
  • Adding option as a third argument to the function wouldn't be so much of a burden
  • _type is really not necessary. The only use case for it is the converters.img function, but that wouldn't be a problem

On the other hand, changing the API could lead to broken dependants, but even that wouldn't be so much of a problem, since _type isn't part of the Public API and shouldn't be used by external libraries anyway.

I implemented these changes and made them available on my fork.
If only a subset of them is acceptable, that's totally alright!
Please let me know what you think.

Support for images alt

json2md({
  img: {
    source: "source",
    title: "title",
    alt: "alt"
  }
}

should transform to ![alt](source "title").

Json to front matter markdown

Hello, Thank you for your amazing lib.

Like you saw by yourself, I used your lib to create markdown content for my Gatsby-source-google-docs plugin.

But what about supporting full markdown features like front metadata?

For now I do a simple conversion but I'm not very happy with this because it could be more complicated, for exemple if I have some nested arrays in front matter.

Do you plan to support this ?

You could use an optional second argument:

json2md([{ h1: "JSON To Markdown" }], {
  tags: ["tag1", "tag2"], 
  authors: [
    {name: "author1", email: "author1@"}, 
    {name: "author2", email: "author2@"}
  ]
})

should transform to

--- 
tags:
  - tag1
  - tag2
authors:
  - name: author1
    email: author1@
  - name: author2
    email: author2@
--- 
# JSON To Markdown

Thank you very much

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.