...

Source file src/github.com/launchdarkly/go-jsonstream/v3/jwriter/writer_object.go

Documentation: github.com/launchdarkly/go-jsonstream/v3/jwriter

     1  package jwriter
     2  
     3  // ObjectState is a decorator that writes values to an underlying Writer within the context of a
     4  // JSON object, adding property names and commas between values as appropriate.
     5  type ObjectState struct {
     6  	w             *Writer
     7  	hasItems      bool
     8  	previousState writerState
     9  }
    10  
    11  // Name writes an object property name and a colon. You can then use Writer methods to write
    12  // the property value. The return value is the same as the underlying Writer, so you can chain
    13  // method calls:
    14  //
    15  //	obj.Name("myBooleanProperty").Bool(true)
    16  func (obj *ObjectState) Name(name string) *Writer {
    17  	if obj.w == nil || obj.w.err != nil {
    18  		return &noOpWriter
    19  	}
    20  	if obj.hasItems {
    21  		if err := obj.w.tw.Delimiter(','); err != nil {
    22  			obj.w.AddError(err)
    23  			return obj.w
    24  		}
    25  	}
    26  	obj.hasItems = true
    27  	obj.w.AddError(obj.w.tw.PropertyName(name))
    28  	return obj.w
    29  }
    30  
    31  // Maybe writes an object property name conditionally depending on a boolean parameter.
    32  // If shouldWrite is true, this behaves the same as Property(name). However, if shouldWrite is false,
    33  // it does not write a property name and instead of returning the underlying Writer, it returns
    34  // a stub Writer that does not produce any output. This allows you to chain method calls without
    35  // having to use an if statement.
    36  //
    37  //	obj.Maybe(shouldWeIncludeTheProperty, "myBooleanProperty").Bool(true)
    38  func (obj *ObjectState) Maybe(name string, shouldWrite bool) *Writer {
    39  	if obj.w == nil {
    40  		return &noOpWriter
    41  	}
    42  	if shouldWrite {
    43  		return obj.Name(name)
    44  	}
    45  	return &noOpWriter
    46  }
    47  
    48  // End writes the closing delimiter of the object.
    49  func (obj *ObjectState) End() {
    50  	if obj.w == nil || obj.w.err != nil {
    51  		return
    52  	}
    53  	obj.w.AddError(obj.w.tw.Delimiter('}'))
    54  	obj.w.state = obj.previousState
    55  	obj.w = nil
    56  }
    57  

View as plain text