Skip to content

✍️ WriteComposerJSON

Serializes a ComposerJSON struct into indented JSON and writes it back to the composer.json file in the working directory.

When to use

Use this when you have modified the struct fields of composer.json through code (e.g. directly editing Require, Scripts, and other maps) and need to persist the changes to disk. This method is typically paired with ReadComposerJSON: read first, modify the in-memory object, then write back.

Signature

go
func (c *Composer) WriteComposerJSON(composerJSON *ComposerJSON) error

Parameters

ParameterTypeDescription
composerJSON*ComposerJSONPointer to the composer.json struct to write

Return value

  • error: returned when serialization or file writing fails; nil on success.

Example

go
package main

import (
	"log"

	"github.com/scagogogo/composer-skills/pkg/composer"
)

func main() {
	comp, err := composer.New(composer.DefaultOptions())
	if err != nil {
		log.Fatal(err)
	}

	data, err := comp.ReadComposerJSON()
	if err != nil {
		log.Fatal(err)
	}

	// Modify the project description
	data.Description = "An even better PHP library"

	if err := comp.WriteComposerJSON(data); err != nil {
		log.Fatalf("write composer.json failed: %v", err)
	}
}

Advanced

  • 📝 Writing uses json.MarshalIndent with 4-space indentation; the file permission is 0644.
  • ⚠️ This method overwrites composer.json in full; custom fields not mapped in the struct will be lost. To preserve unknown fields, operate on the raw file directly or use a more permissive map[string]interface{}.
  • 🔗 Common write wrappers: AddRequire, RemoveRequire, AddScript, SetProperty.

Released under the MIT License