Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string into map Golang

I have a string like A=B&C=D&E=F, how to parse it into map in golang?

Here is example on Java, but I don't understand this split part

String text = "A=B&C=D&E=F";
Map<String, String> map = new LinkedHashMap<String, String>();
for(String keyValue : text.split(" *& *")) {
   String[] pairs = keyValue.split(" *= *", 2);
   map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
like image 441
Bran S Avatar asked Feb 26 '16 23:02

Bran S


People also ask

How to convert string into map in golang?

To convert JSON String to Map object in Go language, import the package encode/json, call json. Unmarshall() function and pass the JSON String as byte array, and address of an empty map as arguments to the function. The function transforms the JSON string to map, and loads the result at given map address.

How do I create a Golang map?

Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.

What does map string interface{} mean?

map[string]interface{} is a map whose keys are strings and values are any type.

When to use map string interface?

When to use map[string]interface{}? The “map of string to empty interface” type is very useful when we need to deal with data; arbitrary JSON data(the data in any format)of an unknown schema.


1 Answers

Maybe what you really want is to parse an HTTP query string, and url.ParseQuery does that. (What it returns is, more precisely, a url.Values storing a []string for every key, since URLs sometimes have more than one value per key.) It does things like parse HTML escapes (%0A, etc.) that just splitting doesn't. You can find its implementation if you search in the source of url.go.

However, if you do really want to just split on & and = like that Java code did, there are Go analogues for all of the concepts and tools there:

  • map[string]string is Go's analog of Map<String, String>
  • strings.Split can split on & for you. SplitN limits the number of pieces split into like the two-argument version of split() in Java does. Note that there might only be one piece so you should check len(pieces) before trying to access pieces[1] say.
  • for _, piece := range pieces will iterate the pieces you split.
  • The Java code seems to rely on regexes to trim spaces. Go's Split doesn't use them, but strings.TrimSpace does something like what you want (specifically, strips all sorts of Unicode whitespace from both sides).

I'm leaving the actual implementation to you, but perhaps these pointers can get you started.

like image 146
twotwotwo Avatar answered Sep 30 '22 11:09

twotwotwo