//Helper function to import json from file to map
514489
func importJSONDataFromFile(fileName string, result interface{}) (isOK bool) {
	isOK = true
	content, err := ioutil.ReadFile(fileName)
	if err != nil {
		fmt.Print("Error:", err)
		isOK = false
	}
	err = json.Unmarshal(content, result)
	if err != nil {
		isOK = false
		fmt.Print("Error:", err)
	}
	return
}
915612
func JSON(l *Slog) ([]byte, error) {
	m := strings.Replace(l.Log.FormatMessage(), "\n", " ", -1)
	if len(m) > 0 && m[len(m)-1] == ' ' {
		m = m[:len(m)-1]
	}
	buf := Pool.Get().([]byte)
	buf = append(buf, domain...)
	buf = append(buf, l.Log.Domain...)
	buf = append(buf, prio...)
	buf = append(buf, l.Log.Priority.Byte()...)
	buf = append(buf, ts...)
	formatJSONTime(&buf, l.Log.Timestamp)
	buf = append(buf, l.Log.zoneBuf...)
	buf = append(buf, tgs...)
	l.Log.Tags.EncodeJSON(&buf)
	buf = append(buf, msg...)
	buf = append(buf, []byte(m)...)
	buf = append(buf, file...)
	if l.Log.DoDi {
		buf = append(buf, []byte(l.Log.file)...)
	}
	buf = append(buf, closeing...)
	return buf, nil
}
30869
func LoadJSON(jsonContent []byte) (*Dataset, error) {
	var input []map[string]interface{}
	if err := json.Unmarshal(jsonContent, &input); err != nil {
		return nil, err
	}

	return internalLoadFromDict(input)
}
1137878
func Import(name string, s Writer, reader io.Reader) error {
	tr := tar.NewReader(reader)
	tlsData := ContextTLSData{
		Endpoints: map[string]EndpointTLSData{},
	}
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		if hdr.Typeflag == tar.TypeDir {
			// skip this entry, only taking files into account
			continue
		}
		if hdr.Name == metaFile {
			data, err := ioutil.ReadAll(tr)
			if err != nil {
				return err
			}
			var meta Metadata
			if err := json.Unmarshal(data, &meta); err != nil {
				return err
			}
			meta.Name = name
			if err := s.CreateOrUpdate(meta); err != nil {
				return err
			}
		} else if strings.HasPrefix(hdr.Name, "tls/") {
			relative := strings.TrimPrefix(hdr.Name, "tls/")
			parts := strings.SplitN(relative, "/", 2)
			if len(parts) != 2 {
				return errors.New("archive format is invalid")
			}
			endpointName := parts[0]
			fileName := parts[1]
			data, err := ioutil.ReadAll(tr)
			if err != nil {
				return err
			}
			if _, ok := tlsData.Endpoints[endpointName]; !ok {
				tlsData.Endpoints[endpointName] = EndpointTLSData{
					Files: map[string][]byte{},
				}
			}
			tlsData.Endpoints[endpointName].Files[fileName] = data
		}
	}
	return s.ResetTLSMaterial(name, &tlsData)
}
1334846
func (env *Env) Import(r io.Reader) error {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "#") || len(line) == 0 {
			continue
		}
		l := strings.SplitN(line, "=", 2)
		if len(l) == 1 {
			return fmt.Errorf("Invalid line: %q", line)
		}
		env.data[l[0]] = l[1]

	}

	return scanner.Err()
}
695569
func ReadFileJSON(file string, v interface{}) error {
	bytes, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	return json.Unmarshal(bytes, v)
}
498485
func TranslatedMap(ctx context.Context, sourceInterface interface{}) map[string]interface{} {
	iType := reflect.TypeOf(sourceInterface).Elem()
	result := make(map[string]interface{})

	for i := 0; i < iType.NumField(); i++ {
		fieldName := reflect.TypeOf(sourceInterface).Elem().Field(i).Name
		fieldValue := reflect.ValueOf(sourceInterface).Elem().Field(i).String()

		result[fieldName] = Translate(ctx, fieldValue)
	}

	return result
}
1307748
func ConvertDoc(r io.Reader) (string, map[string]string, error) {
	f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
	if err != nil {
		return "", nil, fmt.Errorf("error creating local file: %v", err)
	}
	defer f.Done()

	// Meta data
	mc := make(chan map[string]string, 1)
	go func() {
		meta := make(map[string]string)
		metaStr, err := exec.Command("wvSummary", f.Name()).Output()
		if err != nil {
			// TODO: Remove this.
			log.Println("wvSummary:", err)
		}

		// Parse meta output
		for _, line := range strings.Split(string(metaStr), "\n") {
			if parts := strings.SplitN(line, "=", 2); len(parts) > 1 {
				meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
			}
		}

		// Convert parsed meta
		if tmp, ok := meta["Last Modified"]; ok {
			if t, err := time.Parse(time.RFC3339, tmp); err == nil {
				meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
			}
		}
		if tmp, ok := meta["Created"]; ok {
			if t, err := time.Parse(time.RFC3339, tmp); err == nil {
				meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
			}
		}

		mc <- meta
	}()

	// Document body
	bc := make(chan string, 1)
	go func() {

		// Save output to a file
		outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-")
		if err != nil {
			// TODO: Remove this.
			log.Println("TempFile Out:", err)
			return
		}
		defer os.Remove(outputFile.Name())

		err = exec.Command("wvText", f.Name(), outputFile.Name()).Run()
		if err != nil {
			// TODO: Remove this.
			log.Println("wvText:", err)
		}

		var buf bytes.Buffer
		_, err = buf.ReadFrom(outputFile)
		if err != nil {
			// TODO: Remove this.
			log.Println("wvText:", err)
		}

		bc <- buf.String()
	}()

	// TODO: Should errors in either of the above Goroutines stop things from progressing?
	body := <-bc
	meta := <-mc

	// TODO: Check for errors instead of len(body) == 0?
	if len(body) == 0 {
		f.Seek(0, 0)
		return ConvertDocx(f)
	}
	return body, meta, nil
}
700191
func (s *Map) Error() string {
	bytes, err := json.Marshal(s)
	resp := "Unable to format Map"
	if err == nil {
		resp = string(bytes)
	}
	return resp
}
605044
func convertMap(in map[interface{}]interface{}) map[string]interface{} {
  rtn := make(map[string]interface{})
  for key, val := range in {
    // if the value is a map of interface interfaces
    // make sure to convert them as well    
    var newValue interface{}
    switch val.(type) {
      case []interface{}:
        newValue = convertArray(val.([]interface{}))
      case map[interface{}]interface{}:
        newValue = convertMap(val.(map[interface{}]interface{}))
      default:
        newValue = val
    }

    switch key.(type) {
    case string:
      rtn[key.(string)] = newValue
    }
  }

  return rtn  
}
1288979
func PrettyPrintJSONMap(jsonMap map[string]interface{}) {
	result, _ := json.MarshalIndent(jsonMap, "", "   ")
	log.Printf(string(result))
}
847832
func fillJsonMap(json2ptr *map[string]*HashFieldDet, fx *[]Sexp, fl *[]reflect.StructField, embedPath []EmbedPath, tye reflect.Type, detOrder *[]*HashFieldDet) {
	var suffix string
	if len(embedPath) > 0 {
		suffix = fmt.Sprintf(" embed-path<%s>", GetEmbedPath(embedPath))
	}
	m := tye.NumField()
	for i := 0; i < m; i++ {
		fld := tye.Field(i)
		*fl = append(*fl, fld)
		*fx = append(*fx, &SexpStr{S: fld.Name + " " + fld.Type.String() + suffix})
		det := &HashFieldDet{
			FieldNum:     i,
			FieldType:    fld.Type,
			StructField:  fld,
			FieldName:    fld.Name,
			FieldJsonTag: fld.Name, // fallback. changed below if json tag available.
		}
		jsonTag := fld.Tag.Get("json")
		if jsonTag != "" {
			det.FieldJsonTag = jsonTag
			(*json2ptr)[jsonTag] = det
		} else {
			(*json2ptr)[fld.Name] = det
		}
		*detOrder = append(*detOrder, det)
		det.EmbedPath = append(embedPath,
			EmbedPath{ChildName: fld.Name, ChildFieldNum: i})
		if fld.Anonymous {
			// track how to get at embedded struct fields
			fillJsonMap(json2ptr, fx, fl, det.EmbedPath, fld.Type, detOrder)
		}
	}
}
252771
func LoadJSON(raw json.RawMessage) (*Config, error) {
	obj, err := hcl.Parse(string(raw))
	if err != nil {
		return nil, fmt.Errorf(
			"Error parsing JSON document as HCL: %s", err)
	}

	// Start building the result
	hclConfig := &hclConfigurable{
		Root: obj,
	}

	return hclConfig.Config()
}
987918
func (s service) Imports() []string {
	if !s.UnmarshallResponse {
		return nil
	}

	ipMap := map[string]struct{}{
		"from .unmarshall_error import UnmarshallError":      struct{}{},
		"from .unhandled_api_error import UnhandledAPIError": struct{}{},
	}
	for _, m := range s.Methods {
		for _, importLine := range m.imports() {
			ipMap[importLine] = struct{}{}
		}
	}
	return commons.MapToSortedStrings(ipMap)
}
591603
func (c Context) Map(values ...interface{}) (map[string]interface{}, error) {
	if len(values)%2 != 0 {
		return nil, fmt.Errorf("Map expects an even number of arguments")
	}
	dict := make(map[string]interface{}, len(values)/2)
	for i := 0; i < len(values); i += 2 {
		key, ok := values[i].(string)
		if !ok {
			return nil, fmt.Errorf("Map keys must be strings")
		}
		dict[key] = values[i+1]
	}
	return dict, nil
}
46947
func (d *Databook) JSON() (*Exportable, error) {
	b := newBuffer()
	b.WriteString("[")
	for _, s := range d.sheets {
		b.WriteString("{\"title\": \"" + s.title + "\", \"data\": ")
		js, err := s.dataset.JSON()
		if err != nil {
			return nil, err
		}
		b.Write(js.Bytes())
		b.WriteString("},")
	}
	by := b.Bytes()
	by[len(by)-1] = ']'
	return newExportableFromBytes(by), nil
}
301520
func (p *Path) ToGeoJSON() *geojson.Feature {
	coords := make([][]float64, 0, len(p.PointSet))

	for _, p := range p.PointSet {
		coords = append(coords, []float64{p[0], p[1]})
	}

	return geojson.NewLineStringFeature(coords)
}