Reputation: 9262
How would you recommend converting a text file to JSON format?
I have a text file with about 500 bits of text in the following format:
[number in brackets or astriek]
[line1]
[line2]
[line3]
[space]
.
.
.
I want to convert it to JSON, like so:
"page1": {
"line1": "LINE1",
"line2": "LINE2",
"line3": "LINE3"
},
"page2": {
"line1": "LINE1",
"line2": "LINE2",
"line3": "LINE3"
}
.
.
.
Ideas?
Upvotes: 8
Views: 65858
Reputation: 1466
Using Visual Studio
If you have the required data in a text file, this will be the best option.
Open Visual Studio and under File menu --> New --> File Under the installed, you should have the "Web" option. One of the formats listed there is JSON.
Select that and Copy and Paste your text document in VS. Save the file and it is in JSON format.
Upvotes: -1
Reputation: 382150
The simplest for me would be do to it in java or go.
In Java :
readLine
using a new BufferedReader(new FileReader(file))
HashMap
of HashMap<String,String>
during the readingnew BufferedWriter(new FileWriter(outputfilepath))
this :
Gson gson = new Gson();
gson.toJson(myList, myFileOutputStreamWriter);
In Go :
You don't need to import an external package, Go includes the needed ones.
This would be something like this (some other error testing would 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)
}
Upvotes: 2
Reputation: 3357
You could use Gelatin.
You'd use a grammar to define your input text (can be a little difficult if you've never done it before). Then you just run your text file through Gelatin with your grammar file, and specify the output.
Edit 1: It would be helpful if you would post a snippet of what you are trying to convert.
Upvotes: 3