Home  >  Article  >  Web Front-end  >  Convert URL to JSON format

Convert URL to JSON format

不言
不言Original
2018-07-05 17:27:344109browse

This article mainly introduces the conversion of URL into JSON format. It has certain reference value. Now I share it with you. Friends in need can refer to it.

There are many online methods and various tricks. Damn it, here is a more normal idea.
Mainly use split to continuously split the obtained string, and finally obtain the required format.
The code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>将url转化为json数据</title>
</head>
<script>
    function queryString(url){
        let arr=[]; //存储参数的数组
        let res={}; //存储最终JSON结果对象
        arr=url.split("?")[1].split("&"); //arr=["a=1", "b=2", "c=test", "d"]

        for(let i=0,len=arr.length;i<len;i++){
            //如果有等号,则执行赋值操作
            if(arr[i].indexOf("=")!=-1){
                let str=arr[i].split("=");
                //str=[a,1];
                res[str[0]]=str[1];
            }else{//没有等号,则赋予空值
                res[arr[i]]="";
            }
        }
        res=JSON.stringify(res);//转化为JSON字符串
        return res; //{"a": "1", "b": "2", "c": "test", "d": ""}
    }
    console.log(queryString(&#39;www.baidu.com?a=1&b=2&c=test&d&#39;));
</script>
<body>  
</body>
</html>

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to get index when elementui and el-upload are used in v-for

The above is the detailed content of Convert URL to JSON format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn