construct a url with input parameters from json - javascript

I am receiving a json response to construct a parameterized string in JavaScript. However I need to pass actual parameters from JavaScript on some properties e.g. custom_input has to change dynamically.
[{
"road_name_gr": "custom_input"
"town_code" : 1
}]
Then I read that json file and convert that to a url.
cql_filter = new URLSearchParams(json_file).toString();
output: town_code=1&road_name_gr=custom_input
However I have to "modify" the url to accept input.
e.g. 'town_code=1&road_name_gr=' + my_custom_input

Try this:
my_custom_input = decodeURIComponent(my_custom_input) // URI Decode
let input_params = new URLSearchParams(json_file);
input_params.set("road_name_gr", my_custom_input);
cql_filter = input_params.toString();
You have to set parameter before obtain string value.

Related

how to make PHP interpret URL GET parameters as array?

I'm trying to interpret an array url param in PHP, but it's interpreted as string instead of an array.
On client side, the url is generated with js:
URL:
let url = window.location.href.split('?')[0] //example https://www.test.com
The get parameters are added with:
const params = encodeURIComponent(JSON.stringify(array));
url += "?array="+params;
for an example array of [1010,1020,1030], the final url looks like:
https://www.test.com?array=%5B%221010%22%2C%221020%22%2C%221030%22%5D
On server side (PHP), I'm using $_GET['array'] to get those data, the output looks like:
string(22) "["1010","1020","1030"]"
It is a syntactically correct array, but interpreted as string.
I know, I could use some string manipulations to get the array I want, but is there a way, that I can get an array right from scratch?
Either decode the current parameters as JSON...
$array = json_decode($_GET['array']);
or encode the array in a way PHP understands natively...
const params = new URLSearchParams();
array.forEach((val) => {
params.append("array[]", val); // note the "[]" suffix
});
url += `?${params}`;
$array = $_GET['array'] ?? [];

URLSearchParams is not giving correct parameter values

I am trying to use URLSearchParams to extract the url parameters whose values are AES encrypted. But I noticed that if the value contains '+' sign, URLSearchParams is not giving proper value.
For example, if url is 'https://www.google.com/?data=a+b', URLSearcParams is giving data as 'a b'. I am using below code.
var url = new URL('https://www.google.com/?data=a+b')
url.searchParams.get('data')
Can anyone please let me know, if there is any other way to extract the url parameter values.
You must use searchParams.append() in order to set querystring params properly. I made a simple object with all keys + values and then a helper function to append the contents of the objec properly:
const url = new URL('https://www.google.com/')
const params = {
'data': 'a+b',
'moarData': 'c+d'
};
Object.entries(params).forEach(([key, val]) => url.searchParams.append(key, val));
console.log(url.searchParams.get('data'));
console.log(url.searchParams.get('moarData'));

Extract query string from local a href

I'm writing a tweak script / extension to an existing website. There is a <a href that points to a local file (like <a href='/thing.php?id=123&section=456'>) I want to extract the id, 123 in that case. Currently it does $('#theID').attr('href').split('&')[0].split('=')[1]); which is cursed.
However, I cannot do new URL($('#theID').attr('href')).searchParams.get('id') because I get Uncaught TypeError: URL constructor: /thing.php?id=123&section=456 is not a valid URL. How can I properly parse this?
Since you are retrieving the URL from an anchor tag, you can use its properties. The query string can be retrieved from the search property. Then you can manually parse the query string or use the new URLSearchParams feature to parse it.
For example:
var a = document.getElementById("test");
var search = a.search;
var parsed = new URLSearchParams(search);
var q = parsed.get("q");
alert(q);
https://jsfiddle.net/uwo2a17p/

How to store and retrieve JSON data into local storage?

I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}

putting json into javascript variable

I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers

Categories