Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve comments on source file #51

Closed
mohsenari opened this issue Nov 29, 2022 · 3 comments
Closed

Preserve comments on source file #51

mohsenari opened this issue Nov 29, 2022 · 3 comments

Comments

@mohsenari
Copy link

mohsenari commented Nov 29, 2022

I was wondering if there is a way to Unmarshal hjson to a go struct but preserve arbitrary comments on the source json. For example if my hjson looks like this:

{
// random comment
  "foo": "bar",
  "foo2": "bar2"
}

I want to preserve a comment on a random line in the json, unmarshal the file to a go struct, change bar to bar-modified.
Then marshal and save to file.

Is it possible to preserve comments when you don't know which line might have a comment on it?

@trobro
Copy link
Member

trobro commented Nov 29, 2022

I don't know of any solution for structs, because the tags on structs are declared in the struct declaration and cannot be altered after that.

One solution I could do is to create a special hjson.Value interface in hjson-go similar to the Value class in hjson-cpp. So that Hjson can be unmarshalled into a tree of hjson.Value objects where comments can be read and written on each object.

@mohsenari
Copy link
Author

Yeah I think that could work. To be clear my goal is not to read & write comments even though it would be a nice feature to have. My goal is to preserve comments, and change the key-value data. Then save my changed data back to json while keeping the comments unchanged.

@trobro
Copy link
Member

trobro commented Dec 11, 2022

In the new release v4.3.0 you can read-change-write with preserved comments and whitespace for example like this:

var node hjson.Node
if err := hjson.Unmarshal(txt, &node); err != nil {
  panic(err)
}
if _, _, err := node.SetKey("myKey", "myValue"); err != nil {
  panic(err)
}
outBytes, err := hjson.Marshal(node)
if err != nil {
  panic(err)
}

@trobro trobro closed this as completed Dec 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants