Skip to content

Commit

Permalink
✨ feat: read json dataset from file #5
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Jan 20, 2025
1 parent 5fe60c2 commit a77b432
Show file tree
Hide file tree
Showing 4 changed files with 562 additions and 0 deletions.
97 changes: 97 additions & 0 deletions fj.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fj

import (
"io"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -94,6 +95,61 @@ func Parse(json string) Context {
return value
}

// ParseBufio reads a JSON string from an `io.Reader` and parses it into a Context.
//
// This function combines the reading and parsing operations. It first reads the JSON
// string using the `BufioRead` function, then processes the string using the `Parse`
// function to extract details about the first valid JSON element. If reading the JSON
// fails, the returned Context contains the encountered error.
//
// Parameters:
// - in: An `io.Reader` from which the JSON string will be read. This could be a file,
// network connection, or any other source that implements the `io.Reader` interface.
//
// Returns:
// - A `Context` representing the parsed JSON element. If an error occurs during the
// reading process, the `err` field of the `Context` is set with the error, and the
// other fields remain empty.
//
// Example Usage:
//
// // Reading JSON from a file
// file, err := os.Open("example.json")
// if err != nil {
// log.Fatal(err)
// }
// defer file.Close()
//
// ctx := ParseBufio(file)
// if ctx.err != nil {
// log.Fatalf("Failed to parse JSON: %v", ctx.err)
// }
// fmt.Println(ctx.kind)
//
// // Reading JSON from standard input
// fmt.Println("Enter JSON:")
// ctx = ParseBufio(os.Stdin)
// if ctx.err != nil {
// log.Fatalf("Failed to parse JSON: %v", ctx.err)
// }
// fmt.Println(ctx.kind)
//
// Notes:
// - This function is particularly useful when working with JSON data from streams or large files.
// - The `Parse` function is responsible for the actual parsing, while this function ensures the
// JSON string is read correctly before parsing begins.
// - If the input JSON is malformed or invalid, the returned Context from `Parse` will reflect
// the issue as an empty Context or an error in the `err` field.
func ParseBufio(in io.Reader) Context {
json, err := BufioRead(in)
if err != nil {
return Context{
err: err,
}
}
return Parse(json)
}

// ParseBytes parses a JSON byte slice and returns a Context representing the parsed value.
//
// This function is a wrapper around the `Parse` function, designed specifically for handling JSON data
Expand Down Expand Up @@ -1579,6 +1635,47 @@ func (ctx Context) Less(token Context, caseSensitive bool) bool {
return ctx.unprocessed < token.unprocessed
}

// IsError checks if there is an error associated with the Context.
//
// This function checks whether the `err` field of the Context is set. If there is
// an error (i.e., `err` is not `nil`), the function returns `true`; otherwise, it returns `false`.
//
// Example Usage:
//
// ctx := Context{err: fmt.Errorf("invalid JSON")}
// fmt.Println(ctx.IsError()) // Output: true
//
// ctx = Context{}
// fmt.Println(ctx.IsError()) // Output: false
//
// Returns:
// - bool: `true` if the Context has an error, `false` otherwise.
func (ctx Context) IsError() bool {
return ctx.err != nil
}

// ErrMessage returns the error message if there is an error in the Context.
//
// If the Context has an error (i.e., `err` is not `nil`), this function returns
// the error message as a string. If there is no error, it returns an empty string.
//
// Example Usage:
//
// ctx := Context{err: fmt.Errorf("parsing error")}
// fmt.Println(ctx.ErrMessage()) // Output: "parsing error"
//
// ctx = Context{}
// fmt.Println(ctx.ErrMessage()) // Output: ""
//
// Returns:
// - string: The error message if there is an error, or an empty string if there is no error.
func (ctx Context) ErrMessage() string {
if ctx.IsError() {
return ctx.err.Error()
}
return ""
}

// parseJSONElements processes a JSON string (from the `Context`) and attempts to parse it as either a JSON array or a JSON object.
//
// The function examines the raw JSON string and determines whether it represents an array or an object by looking at
Expand Down
67 changes: 67 additions & 0 deletions h.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,73 @@ import (
"github.com/sivaosorg/unify4g"
)

// LastNLines returns the last `num` lines from the given slice of strings.
//
// This function extracts the last `num` lines from a slice of strings (`lines`).
// If `num` is greater than the number of lines available, it returns all lines.
// If `num` is less than or equal to 0, it returns an empty slice.
//
// Parameters:
// - lines: A slice of strings representing the input lines.
// - num: An integer specifying the number of lines to retrieve from the end.
//
// Returns:
// - A slice of strings containing the last `num` lines from the input.
// If `num` is greater than the length of `lines`, all lines are returned.
// If `num` is less than or equal to 0, an empty slice is returned.
//
// Details:
// - The function calculates the starting index for slicing the input lines by
// subtracting `num` from the total length of the lines. If the result is negative,
// it starts from the beginning of the slice.
// - It uses slicing to efficiently extract the last `num` lines.
//
// Example Usage:
//
// // Example: Extracting the last 3 lines from a slice of strings
// lines := []string{
// "Line 1",
// "Line 2",
// "Line 3",
// "Line 4",
// "Line 5",
// }
//
// lastLines := LastNLines(lines, 3)
// for _, line := range lastLines {
// fmt.Println(line)
// }
// // Output:
// // Line 3
// // Line 4
// // Line 5
//
// // Example: Requesting more lines than available
// lastLines = LastNLines(lines, 10)
// for _, line := range lastLines {
// fmt.Println(line)
// }
// // Output:
// // Line 1
// // Line 2
// // Line 3
// // Line 4
// // Line 5
//
// // Example: Requesting zero or negative lines
// lastLines = LastNLines(lines, 0)
// fmt.Println(len(lastLines)) // Output: 0
func LastNLines(lines []string, num int) []string {
if num <= 0 || len(lines) == 0 {
return lines
}
var slices []string
for i := len(lines) - num; i < len(lines); i++ {
slices = append(slices, lines[i])
}
return slices
}

// getNumeric extracts the numeric portion of a JSON-encoded string and converts it to a float.
//
// This function processes a JSON-encoded string to extract a numeric value
Expand Down
Loading

0 comments on commit a77b432

Please sign in to comment.