将json转成MD.table

type JSONStats struct {
	Keys  []string
	Types map[string][]string
}

func parseJSON(prefix string, jsonData []byte, stats *JSONStats) error {
	var data interface{}
	err := json.Unmarshal(jsonData, &data)
	if err != nil {
		return err
	}
	parseJSONObject(prefix, data, stats)
	return nil
}

func parseJSONObject(prefix string, jsonObj interface{}, stats *JSONStats) {
	switch obj := jsonObj.(type) {
	case map[string]interface{}:
		for key, value := range obj {
			if !slices.Contains(stats.Keys, prefix+key) {
				stats.Keys = append(stats.Keys, prefix+key)
			}
			switch value.(type) {
			case []interface{}:
				if !slices.Contains(stats.Types[prefix+key], "array") {
					stats.Types[prefix+key] = append(stats.Types[prefix+key], "array")
				}
				parseJSONArray(prefix+key+".[]", value.([]interface{}), stats)
			case map[string]interface{}:
				if !slices.Contains(stats.Types[prefix+key], "object") {
					stats.Types[prefix+key] = append(stats.Types[prefix+key], "object")
				}
				parseJSONObject(prefix+key+".", value.(map[string]interface{}), stats)
			default:
				nodeType := fmt.Sprintf("%T", value)
				if !slices.Contains(stats.Types[prefix+key], nodeType) {
					stats.Types[prefix+key] = append(stats.Types[prefix+key], fmt.Sprintf("%T", value))
				}
			}
		}
	}
}

func parseJSONArray(prefix string, jsonArray []interface{}, stats *JSONStats) {
	for _, item := range jsonArray {
		switch item.(type) {
		case []interface{}:
			if _, ok := stats.Types[prefix]; !ok {
				stats.Keys = append(stats.Keys, prefix)
				stats.Types[prefix] = append(stats.Types[prefix], "array")
			}
			parseJSONArray(prefix+".[]", item.([]interface{}), stats)
		case map[string]interface{}:
			parseJSONObject(prefix, item.(map[string]interface{}), stats)
		default:
			if _, ok := stats.Types[prefix]; !ok {
				stats.Keys = append(stats.Keys, prefix)
			}
			nodeType := fmt.Sprintf("%T", item)
			if !slices.Contains(stats.Types[prefix], nodeType) {
				stats.Types[prefix] = append(stats.Types[prefix], nodeType)
			}
		}
	}
}

评论列表