Home > Back-end >  Merging two JSON file and reconstructor the JSON by jq
Merging two JSON file and reconstructor the JSON by jq

Time:07-01

I want to use jq tools in shell script to merge two localized json.

Here are the content of files:

ja:

{
    "link_generate": "ランダム化する",
    "label_apple": "リンゴ"
}

en:

{
    "link_generate": "Randomise",
    "label_apple": "Apple"
}

I wanna merge them and create another hierarchy(ja/en) for the duplicate key like:

{
    "link_generate": {
        "en": "Randomise",
        "ja": "ランダム化する"
    },
    "label_apple": {
        "en": "Apple",
        "ja": "リンゴ"
    }
}

CodePudding user response:

Something like

jq -n --slurpfile ja ja.json --slurpfile en en.json '
  [ $en[0] | keys[] | { (.):{ en:$en[0][.], ja:$ja[0][.] } } ] | add'

which outputs

{
  "label_apple": {
    "en": "Apple",
    "ja": "リンゴ"
  },
  "link_generate": {
    "en": "Randomise",
    "ja": "ランダム化する"
  }
}

CodePudding user response:

Here's a solution for an arbitrary number of languages. It uses the first two characters of the filename as language key, and respects an asymmetric population of the dictionaries:

jq -n 'reduce (inputs | to_entries[] | [input_filename[:2], .])
  as [$lang, $ent] ({}; setpath([$ent.key, $lang]; $ent.value))' ja.json en.json

The list of language keys can also be provided separately (hard-coded, or using --arg or --argjson, and in matching order of the input files):

jq -n 'reduce (("ja","en") as $lang | input | to_entries[] | [$lang, .])
  as [$lang, $ent] ({}; setpath([$ent.key, $lang]; $ent.value))' ja.json en.json

Demo

{
  "link_generate": {
    "ja": "ランダム化する",
    "en": "Randomise"
  },
  "label_apple": {
    "ja": "リンゴ",
    "en": "Apple"
  }
}
  • Related