How can I build a querystring from an object? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
querystring encoding of a javascript object
I'm trying to make a request to a website and embed the result as an iframe in the page using javascript. I need to pass a number of parameters in the request as querystring variables and I'd like to be able to specify the parameters as an object, passing them to a function to produce a querystring so they are easy to read, maintain and manipulate.
How can I construct the querystring of a URL from a JSON object with simple values? I would expect this example:
{
h:300,
w:300,
skip:500,
count:50
}
to produce the following querystring:
h=300&w=300&skip=500&count=50
Are there any existing library functions to do this, or is the best thing to loop over the properties myself?

jQuery has a built-in method for this: jQuery.param()

I recommend you use jQuery's param(). Here is the documentation http://api.jquery.com/jQuery.param/
You would pass your object like so:
var myObj = {
h:300,
w:300,
skip:500,
count:50
}
console.log('=>', $.param(myObj) ); // prints => h=300&w=300&skip=500&count=50

Related

Parsing JSON issues [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
fairly new to Javascript, but I have been trying to figure out this parsing issue for several days now and I can't seem to put my finger on what is going on. What I would like to do is get this JSON object into an array or a list of strings into Javascript so that I can use them in my code.
I have a JSON object that I am getting using this URL:
https://min-api.cryptocompare.com/data/all/coinlist
So, I am using the following to grab that object from the URL:
$.getJSON(URL, function(json){
});
to verify that this is indeed a JSON object, I used this which returned "Function Object()"
alert(json.constructor);
So at this point, I have a JSON object inside the variable "json," I would like to start accessing some of the elements. So I try the following:
alert(JSON.stringify(json.Data));
This gives me a popup with all the text from the Data element inside this JSON object, which is great, but I am trying to access the individual items inside "Data." So I try the following which I found here: Accessing JSON elements from javascript :
alert(JSON.stringify(json.Data[1])); AND alert(JSON.stringify(json[1].Data));
Which gets me an "undefined" response. I've then tried turning the "Data" part of this Object into it's own object by using the following:
var DataObj = JSON.parse(json.Data);
console.log(DataObj["Id"]);
But that gives me a "Unexpected token o in JSON at position 1" error.
So I am not sure how to access this Data. I have literally been looking for answers for days and I hate to post what I think is a very amateur question on here but I can't seem to find the answer anywhere online.
Thank you for any help.
json.Data[42].CoinName was an example from Barmar that helped me. Thank you so much

How do I use JS regex to capture a specific JSON value after its key? [duplicate]

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
I have JSON data in the following format:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I can count on the key called "Project": to always be the same.
What I need is to pull the Value of the "Project": key which in this case is "aa2" using regex in JavaScript.
I have been trying different variations of /^("Project":)$/g but it is not working.
My last attempt I tried /[^"Project":$]/g but it gives me everything in the JSON Object but "Project":
Does anyone know how I can capture the value of a specific Project key?
EDIT: Just for clarification I agree with the use of the Parsing mechanism. My problem is that I am debugging/working with a previous code base that is using a separate function to pass the parsed JSON as a string into the function where now I need to pull the data needed from the string. After having spent this amount of time trying to come up with a work around I am about to scrap the function in order to use Parse... that's why I'm trying to use regex but the more I think about it, the more I realize that it's just bad code... but still, now I am just curious.
No need to use Regular expression to extract value from object string. Just Use JSON.parse(). This will convert string to Object. After parsing you can use key to access the value.
var obj = JSON.parse('{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}');
console.log(obj.Project);
Parse the JSON and then get the value.
Working example : https://jsfiddle.net/vineeshmp/2c8z7r6u/
var json =' {"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}';
json = JSON.parse(json);
alert(json.Project);

How to use a bit complex object as a value of a key in localStorage of Google Chrome? [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 6 years ago.
I'm trying to build a chrome extension that would feed data in the localStorage of the form:
var a = 'YouTube';
var data = {
'title': 'twenty one pilots: Stressed Out [OFFICIAL VIDEO]',
'url': 'https://www.youtube.com/watch?v=pXRviuL6vMY'
};
localStorage.setItem(a, data);
But when I look into the resources in dev. tools, it doesn't show the data object in the value table. How can I make it appear in there?What's wrong with the code?
The Image of the console and the localStorage.
I have tried commands like localStorage.YouTube and localStorage.getItem('YouTube') but it always returns [object Object].
What could be a possible workaround for making something like this possible?
LocalStorage in HTML5 can only store key-values strings. You can't store objects there.
BUT, you can use JSON. To make a string from your object you can use JSON.stringify(yourObj);
and when you want to get value from LocalStorage you simply parse that string and create new object which you can use again. JSON.parse(yourObj);

Passing variable into Backbone.where [duplicate]

This question already has an answer here:
Trouble referencing variable in Collections.where method within render function
(1 answer)
Closed 7 years ago.
I want to form a collection from a JSON based on the obtained value and Backbone's where seemed like a perfect tool, but it looks like it doesn't accept variables. Is it possible to achieve this sort of functionality using some of Backbone, Lodash or Underscore methods?
### collection instantiated above
App.vent.on 'event', (obtained_value) ->
desired_models = collection.where(attribute: obtained_value)
console.log desired_models
### outputs empty array
>[]
It does work when I pass key: value directly, but I need to form collection dynamically. Maybe I've initially taken a false route and the solution is in the another direction?
I'm assuming your goal is to vary the attribute you're searching for, since if the value is varied, object literals should work fine.
You can do it, just not with an object literal inline. Here's how I would do it in JavaScript:
App.vent.on('event', function (obtainedValue) {
var finder = {};
finder[attribute] = obtainedValue;
desiredModels = collection.where(finder);
console.log(desiredModels);
});
that wont work, you need to pass an object so it would be like this
collection.where({attribute: obtained_value});
in coffescript you can do the following
attribute_var=
attribute:obtained_value
collection.where(attribute_var);
best regards

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

Categories

Resources