0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nim言語をJavaScriptにトランスパイルして、任意の深さでJSONを整形するWebアプリを作った

Posted at

概要

以前、Nim言語の学習を兼ねて「JSONの深さを指定して整形するCLIツール」を作りました。それなりに便利だったのですが、コマンドラインだとコピペがしづらかったり、手軽に使いたい場面で少し不便に感じることもありました。

そこで今回は、Nim言語をJavaScriptにトランスパイルし、Web上で誰でもすぐに使えるツールとして公開しました。

この記事では、技術的なポイントを交えつつ、実際に作ったものをご紹介します。

デモンストレーション

スクリーンショット 2025-04-16 22.05.09.png

指定した深さでJSONを整形できます。

Nim言語をJavaScriptにトランスパイル

JSONをフォーマットする関数自体は以前に作成済みです。
今回は、それをJavaScriptから呼び出すための入り口(jsonfmtjs.nim)を作成しました。

ここではプラグマを使って、
JavaScriptでjsonfmtという関数をexportしています。

jsonfmtjs.nim
from lib import fmt # 任意の深さでJSONをフォーマットする関数

proc jsonfmt(jsonString: cstring, depth: cint, indent: cint): cstring {.exportc.} =
    fmt($(jsonString), depth, indent)

{. emit: "export { jsonfmt };" .}

ビルドは以下のコマンドで行いました。

nim js -d:release jsonfmtjs.nim

これにより、jsonfmtjs.jsというファイルが生成されます。

jsonfmtjs.jsの末尾
function jsonfmt(jsonString_p0, depth_p1, indent_p2) {
  var result_553648134 = null;

    result_553648134 = toJSStr(fmt__lib_u745(cstrToNimstr(jsonString_p0), ((depth_p1) | 0), ((indent_p2) | 0)));

  return result_553648134;

}
export { jsonfmt };

あとはこれをフロントエンド実装から呼び出すことによって、
JSONを任意の深さで整形できます。

フロントエンド実装からjsonfmtを呼び出す

フロントエンドはVue.js + TypeScriptで作りました。

tsconfig.jsonでJavaScriptの呼び出し許可し、
対象のJSファイルと型定義ファイルを配置してフロントエンドから呼び出すようにしました。

tsconfig.jsonの一部
  "compilerOptions": {
    "allowJs": true,
  }
jsonfmtjs.d.ts
declare module '@/jsonfmtjs.js' {
  export function jsonfmt(input: string, depth: number, indent: number): string
}
フロントエンド実装App.vueの一部
import { jsonfmt } from '@/jsonfmtjs.js'

...

const formattedJson = computed(() => {
  try {
    return jsonfmt(jsonString.value, depth.value, 2)
  } catch (e) {
    console.error(e)
    return 'Failed to format json'
  }
})

今回実装したもののGitリポジトリ

まとめ

今回は、以前Nim言語で作成したJSON整形ツールを、Web上で手軽に使える形に移植する取り組みをご紹介しました。

普段あまり触れる機会の少ないNim言語ですが、こうしたWebアプリ化も意外とスムーズにできる点は発見でした。

もし興味があれば、ぜひデモページも触ってみてください!

homebrewからCLIコマンドも利用可能です:

$ brew tap cacapouh/jsonfmt
$ brew install cacapouh/jsonfmt/jsonfmt
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?