5

In the actual development process, you may encounter scenarios where you need to convert JSON objects into URL parameters, or convert URL parameters into JSON objects. For example, there is a JSON object as follows:

 {
    "type": 1,
    "keyword": "js"
}

Need to be converted into URL parameters: type=1&keyword=js

1. Convert JSON objects to URL parameters

There are two main ways to convert JSON objects into URL parameters. One is to traverse the properties of the JSON object, and the other is to use URLSearchParams . The following is an introduction to the code.

(1) Traverse JSON object properties

Using a loop to traverse the properties of the JSON object and then splicing them together is probably the easiest way to think of. The following is an implementation method of traversing the properties of the JSON object:

 function jsonToUrlParam(json) {
    return Object.keys(json).map(key => key + '=' + json[key]).join('&');
}

have a test

 let json = {
    "type": 1,
    "keyword": "js"
};
console.log(jsonToUrlParam(json));

The output is as follows:

 type=1&keyword=js

In actual application scenarios, a JSON object may have many attributes, but only some attributes are required for URL parameters. At this time, the above method can be modified to ignore the specified attributes, as follows:

 function jsonToUrlParam(json, ignoreFields) {
    return Object.keys(json)
        .filter(key => ignoreFields.indexOf(key) === -1)
        .map(key => key + '=' + json[key]).join('&');
}

Test ignoring the type attribute

 let json = {
    "type": 1,
    "keyword": "js"
};
console.log(jsonToUrlParam(json, ['type']));

The output is as follows:

 keyword=js

(2) URLSearchParams

Regarding URLSearchParams, you can first take a look at the definition of the official https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams

URLSearchParams The interface defines some utility methods to handle URL query strings.

In simple terms, it is used to process the parameter string on the URL, that is, the content of A=B&C=D&E=F after the ?, the beginning '?' characters will be ignored, let's see if it is How to use:

 function jsonToUrlParam(json) {
    return new URLSearchParams(json).toString();
}

have a test

 let json = {
    "type": 1,
    "keyword": "js"
};
console.log(jsonToUrlParam(json));

The output is as follows:

 type=1&keyword=js

2. Convert URL parameters to JSON objects

For example, there is such a URL: http://example.com?type=1&keyword=js , its parameter part is type=1&keyword=js , how to convert it into a JSON object? The specific implementation code is as follows:

 function urlParamToJson(urlParam) {
    let json = {};
    urlParam.trim()
        .split('&')
        .forEach(item => json[item.split('=')[0]] = item.split('=')[1]);

    return json;
}

have a test

 console.log(JSON.stringify(urlParamToJson('type=1&keyword=js')))

The output is as follows:

 {"type":"1","keyword":"js"}

For this method, you can also transform it, directly pass in a url, then extract the parameter part in the method, and finally convert it, the code is as follows:

 function urlParamToJson(url) {
    if (!url) {
        return {};
    }

    let json = {};
    url.substring(url.indexOf('?') + 1)
        .trim()
        .split('&')
        .forEach(item => json[item.split('=')[0]] = item.split('=')[1]);

    return json;
}

Pass in a url for testing

 console.log(JSON.stringify(urlParamToJson('http://example.com?type=1&keyword=js')))

The output is as follows:

 {"type":"1","keyword":"js"}

十方
226 声望433 粉丝