Convert text to JSON

How do you recommend converting the text file to JSON format?

I have a text file with approximately 500 bits of text in the following format:

[number in brackets or astriek] [line1] [line2] [line3] [space] . . . 

I want to convert it to JSON, for example:

 "page1": { "line1": "LINE1", "line2": "LINE2", "line3": "LINE3" }, "page2": { "line1": "LINE1", "line2": "LINE2", "line3": "LINE3" } . . . 

Ideas?

+6
source share
3 answers

You can use Gelatin .

You should use grammar to define input text (it can be a little tricky if you have never done this before). Then you simply run your text file through Gelatin with your grammar file and specify the result.

Edit 1: It would be helpful if you posted a snippet of what you are trying to convert.

+3
source

The simplest one for me will do it in java or go.

In Java:

  • you can read the file line after the line with readLine using new BufferedReader(new FileReader(file))
  • you can fill the HashMap HashMap<String,String> while reading
  • create new BufferedWriter(new FileWriter(outputfilepath))
  • using gson you just need to use

this is:

 Gson gson = new Gson(); gson.toJson(myList, myFileOutputStreamWriter); 

In Go:

You do not need to import an external package, Go includes the necessary ones.

It will be something like this (some other error checks will be good):

 package main import ( "bufio" "fmt" "io" "encoding/json" "log" "strings" "os" ) func main() { myBigThing := make(map[string]map[string]string) f, _ := os.Open("/home/dys/dev/go/src/tests/test.go") r := bufio.NewReader(f) var currentPage map[string]string pageNum := 0 for { line, err := r.ReadString('\n') if err != nil { if err != io.EOF { log.Println("Error in parsing :", err) } break } if currentPage==nil { currentPage = make(map[string]string) myBigThing[fmt.Sprintf("page%d",pageNum)] = currentPage pageNum++ } else if line=="" { currentPage = nil } else { tokens := strings.Split(line, ":") if len(tokens)==2 { currentPage[tokens[0]] = tokens[1] } } } f, err := os.Create("/home/dys/test.json") if err != nil { log.Println("Error :", err) return } defer f.Close() bout, _ := json.Marshal(myBigThing) f.Write(bout) } 
+2
source

Using Visual Studio

If you have the required data in a text file, this would be the best option.

Open Visual Studio and in the menu File → New → File. According to what you have installed, you should have the option "Internet". One of the formats available here is JSON.

Select this and copy and paste your text document into VS. Save the file and it is in JSON format.

0
source

Source: https://habr.com/ru/post/919343/


All Articles