“This is the 9th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

directory

  • preface
  • The body of the
  • At the end

preface

Today, I met a small pit, but I have been stuck in it for a long time. It is a little embarrassed to say so, but I still feel that I should take it out and share it with you. I hope you will not be delayed by similar problems again.

Parse the following JSON structure:

"video": {
        "width": 1280."height": 720
}
Copy the code

First, let’s simplify the problem. Suppose we have a video instance of type MAP [string]interface{}, how to read width and height based on the video instance. Note that the values are integer values, not strings.

The body of the

The original plan

According to our abstract out of the problem, the solution idea is also very clear, we first according to the string type key, namely width and height interface object W and H. The interface type is then cast to get the final int integer value.

Int int int int int int int int int int int int int int int int int int

interface conversion: interface {} is float64, not int

The specific code is as follows:

w := video["width"]
h := video["height"]
ifw ! = nil && h ! = nil {width := w.(int)
        height := h.(int)
        logger.Infof("width:%d, height:%d", width, height)
        ifwidth ! =0&& height ! =0 {
                output.Dimensions = strconv.Itoa(width) + "x" + strconv.Itoa(height)
        }
}
Copy the code

Final plan

Interface {} interface type can not be directly converted into an int integer type, I always suspected that there was a problem in the coding details, so I went astray.

The end result is multiple implementations, but none of them fundamentally different. Interface {} is a float64 interface. If you want to get an int value, you need to convert it to float.

Therefore, a final solution was found.

The final code implementation is as follows:

w := video["width"]
h := video["height"]
ifw ! = nil && h ! = nil {width := int(w.(float64))
        height := int(h.(float64))
        logger.Infof("width:%d, height:%d", width, height)
        ifwidth ! =0&& height ! =0 {
                output.Dimensions = strconv.Itoa(width) + "x" + strconv.Itoa(height)
        }
}
Copy the code

At the end

This was a bit of a pothole in the actual development process, but it made me realize the constant work of filling in the blind spots. Well, that’s all for now.

About the author: Hello, everyone, I am Liuzhen007, an audio and video technology fan, CSDN blog expert, Huawei Cloud community cloud sharing expert, signed the author, welcome to follow me to share more dry products!