3

I have a array of JSON string

ex:

[
 {
  "name":"abc"
  "age":25
 }
 {
  "name":"xyz"
  "age":"26"
 }
]

In run time I want to remove "name" from array . How can we do it . I don't want to unmarshal it .

[
     {
      "age":25
     }
     {
      "age":"26"
     }
  ]
3
  • 1
    If you do not want to unmarshal it, the only way is to parse the bytes yourself, you will end up implementing a state machine. Commented Jul 14, 2017 at 18:31
  • 1
    You might be able to do it with regex if you really must not unmarshel it. Commented Jul 14, 2017 at 18:38
  • 3
    What's wrong with unmarshaling/modifying/marshaling? That seems pretty straightforward. Commented Jul 14, 2017 at 18:57

2 Answers 2

2

you can do what you want by using, this packages gjson, and sjson.

example:

package main

import (
    "fmt"
    "log"
    "strconv"

    "github.com/tidwall/gjson"
    "github.com/tidwall/sjson"
)

func main() {
    bJSON := []byte(`       
            [
                {
                    "name": "abc",
                    "age": 25
                },
                {
                    "name": "xyz",
                    "age": 26
                }
            ]
    `)

    newJSON := bJSON
    var err error

    result := gjson.GetBytes(bJSON, "#.age")

    for i := range result.Array() {
        newJSON, err = sjson.DeleteBytes(newJSON, strconv.Itoa(i)+".age")
        if err != nil {
            log.Println(err)
        }
    }

    fmt.Println(string(newJSON))
}

output:

[
  {
    "name": "abc"
  },
  {
    "name": "xyz"
  }
]
Sign up to request clarification or add additional context in comments.

1 Comment

can we do it without adding "key"
1

If you literally don't want to unmarshal it, you'll be stuck doing some sort of regex replacement, or building a state machine (effectively unmarshaling it yourself). If you're asking the question, then you shouldn't take this approach. This approach is for very advanced users only, and has no advantages except in very extremely rare situations.

I assume you just don't want to bother with the effort of writing code to unmarshal it, though, and wouldn't mind a tool that does the work for you, even if that involves unmarshaling under the covers.

If I'm right in my guess, you could consider a library like gabs (disclaimer: I've never used this library), which provides for easy JSON manipulation. But of course it unmarshals the JSON in the process, then remarshals it when you ask for the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.