Parse a string into a Golang map

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

Here is an example in Java, but I do not 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]); } 
+6
source share
3 answers

Perhaps you really want to parse the HTTP request string, and url.ParseQuery does this. (That it returns, more precisely, url.Values storing []string for each key, since URLs sometimes have more than one value for each key.) It performs actions such as parsing HTML screens ( %0A , etc.). d.) Which simply splitting does not. You can find its implementation if you search for the source url.go

However, if you really want to simply divide by & and = , as the Java code did, there are Go analogues for all concepts and tools:

  • map[string]string is an analogue of Go Map<String, String>
  • strings.Split can be divided by & for you. SplitN limits the number of shared fragments, like the dual-mode version of split() in Java. Please note that there can only be one part, so you should check len(pieces) before trying to access pieces[1] .
  • for _, piece := range pieces will repeat the fragments you split.
  • Java code seems to rely on regular expressions to trim spaces. Go Split does not use them, but strings.TrimSpace does something like what you want (in particular, it removes all kinds of Unicode spaces from both sides).

I leave you with a real implementation, but maybe these pointers will help you get started.

+8
source
 import ( "strings" ) var m map[string]string var ss []string s := "A=B&C=D&E=F" ss = strings.Split(s, "&") m = make(map[string]string) for _, pair := range ss { z := strings.Split(pair, "=") m[z[0]] = z[1] } 

This will do what you want.

+6
source

There is a very simple way provided by the golang net/url package itself.

Modify your string to make it a URL with text := "method://abc.xyz/A=B&C=D&E=F"; request parameters text := "method://abc.xyz/A=B&C=D&E=F";

Now just pass this line to the Parse function provided by net/url .

 import ( netURL "net/url" ) 
 u, err := netURL.Parse(textURL) if err != nil { log.Fatal(err) } 

Now u.Query() will return you a map containing the parameters of your query. This will also work for complex types.

0
source

Source: https://habr.com/ru/post/1243987/


All Articles