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?
you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
notepad++ Useful plugins for developers JSON Viewer It is useful for indenting /formatting JSON documents and can be used to browse complex JSON file using a treeview tool. To format and indent the code: select all the json fragment. click "Plugins"/"JSON Viewer"/"Format JSON" or use the shortcut Ctrl + Alt + Shift + M.
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With