Как отобразить отсутствующие ключи в golang, пройдя через JSON? - PullRequest
0 голосов
/ 12 апреля 2019

Я создаю инструмент перевода для своего приложения.У меня есть 2 разных файла json (en.json, fr.json), где мои ключи и значения:

Файл en.json является ссылочным файлом, что означает необходимость добавления ключей, присутствующих в этом файле.в файле fr.json, если они не существуют.Для получения более подробной информации, если ключ присутствует в файле en.json, а не в файле fr.json, который нам нужно отобразить, но если ключ присутствует только в файле fr.json, он не считается и мы ничего не отображаем на экране.И если ключ уже присутствует в обоих из них, нам не нужно отображать что-либо на экране.

Файл en.json является ссылочным файлом со следующими ключами:

  {
  "i18n-outterJSON": {
        "i18n-value1": "value1",
        "i18n-value2": "value2",
        "i18n-dad" : "dady"
    },
    "InnerJSON2":"NoneValue",
    "hello" : "good morning",
    "onlykey" : "only key",
    "secondekey" : "second key",
    "mother": {
      "daugther": "fille"
    }

}

Файл fr.json является целевым файлом.Со следующими ключами:

    {
  "i18n-outterJSON": {
    "i18n-value1": "value1",
    "i18n-value2": "value2"
  },
  "i18n-hello" : "bonjour",
  "i18n-variation" : "variation",
  "alouette" : "cacahouete",
  "InnerJSON2":"pas de valeur",
  "hello" : "bonjour"
}

Мой код в golang:

fileEnglish := GetAllPathRefFile(); // to open the reference file
  files := GetAllI18nFiles(); // to open the french file

  for _, fileRef := range fileEnglish {
    mapRef := ReadJsonFile(constants.PathRefFile + GetRidOfExtension(fileRef.Name()))

    for _, fileTarget := range files {
      mapTarget := ReadJsonFile(constants.I18nPath + GetRidOfExtension(fileTarget.Name()));
      mapTarget = MissingKey(mapRef, mapTarget)



      // range loop to identify the missing keys in the different files
      for key, _ := range mapRef { // mapRef is the reference map of the reference file en.json
        if  mapRef[key] != mapTarget[key]  { // mapTarget is map of the target file fr.json
          t := strings.Replace(key, key, "", -1)
            _ = t
            fmt.Println("the missing keys are: ", key)
            }
          }
        }
      }

Я пытался сравнить каждый ключ, и в некоторых случаях у нас есть иерархия, и я пытался определить отсутствующиеключи.Мне нужно получить этот результат:

i18n-dad
mother
daughter
onlykey
secondekey

Но с моим текущим кодом у меня есть эта ошибка: comparing uncomparable type map[string]interface {}.

Как мы можем правильно идентифицировать и печатать на экране клавиши?

1 Ответ

0 голосов
/ 12 апреля 2019

Вот быстрый пример, показывающий, чего не хватает во французском JSON, используя https://github.com/go-test/deep.

package main

import (
    "encoding/json"
    "fmt"
    "strings"

    "github.com/go-test/deep"
)

type Data struct {
    I18NOutterJSON struct {
        I18NValue1 string `json:"i18n-value1"`
        I18NValue2 string `json:"i18n-value2"`
        I18NDad    string `json:"i18n-dad"`
    } `json:"i18n-outterJSON"`
    InnerJSON2 string `json:"InnerJSON2"`
    Hello      string `json:"hello"`
    Onlykey    string `json:"onlykey"`
    Secondekey string `json:"secondekey"`
    Mother     struct {
        Daugther string `json:"daugther"`
    } `json:"mother"`
}

func main() {
    enJSON := []byte(`{"i18n-outterJSON":{"i18n-value1":"value1","i18n-value2":"value2","i18n-dad":"dady"},"InnerJSON2":"NoneValue","hello":"good morning","onlykey":"only key","secondekey":"second key","mother":{"daugther":"fille"}}`)
    frJSON := []byte(`{"i18n-outterJSON":{"i18n-value1":"value1","i18n-value2":"value2"},"i18n-hello":"bonjour","i18n-variation":"variation","alouette":"cacahouete","InnerJSON2":"pas de valeur","hello":"bonjour"}`)

    var en, fr Data
    err := json.Unmarshal(enJSON, &en)
    if err != nil {
        panic(err)
    }

    err = json.Unmarshal(frJSON, &fr)
    if err != nil {
        panic(err)
    }

    diff := deep.Equal(en, fr)
    for _, d := range diff {
        if strings.HasSuffix(d, "!= ") {
            fmt.Printf("%s\n", d)
        }
    }
}

$ go run .
I18NOutterJSON.I18NDad: dady != 
Onlykey: only key != 
Secondekey: second key != 
Mother.Daugther: fille != 

Редактировать на основе комментариев. Добавление способа использовать произвольный JSON вместо структуры.

func withArbitraryJSON(enJSON []byte, frJSON []byte) {
    var en map[string]interface{}
    err := json.Unmarshal(enJSON, &en)
    if err != nil {
        panic(err)
    }

    var fr map[string]interface{}
    err = json.Unmarshal(frJSON, &fr)
    if err != nil {
        panic(err)
    }

    diff := deep.Equal(en, fr)
    for _, d := range diff {
        if strings.HasSuffix(d, "!= <does not have key>") {
            fmt.Printf("%s\n", d)
        }
    }
}

Выход:

$ go run .
map[i18n-outterJSON].map[i18n-dad]: dady != <does not have key>
map[onlykey]: only key != <does not have key>
map[secondekey]: second key != <does not have key>
map[mother]: map[daugther:fille] != <does not have key>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...