Home > Web Front-end > JS Tutorial > Convert URL to JSON format

Convert URL to JSON format

不言
Release: 2018-07-05 17:27:34
Original
4174 people have browsed it

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template