Converting a query url to a json - javascript

This is the first time Im asking a question on Stackoverflow, so i excuse in advance if its not properly formulated
I'll keep it it short and simple. I want to convert what i get from this url:
http://hotell.difi.no/api/json/brreg/enhetsregisteret?query=company
to a JSON or array in JavaScript, how do i do this?.
This is going to be a part of a search-webapplication where I just change the query parameter when the user changes the input.
I must admit that I'm completely new at this, and I don't even know if I'm asking the question correctly.

If you want to make a string into a json object, simply use JSON.parse():
var obj = JSON.parse(string);
You can use jQuery.getJSON() if you are using Ajax and you don't mind jQuery:
var obj = $.getJSON( "http://hotell.difi.no/api/json/brreg/enhetsregisteret?query=company", function() {
console.log( "DONE" );
})

Keyword "urlparse javascript"
Node server
url.parse()
Client
This (creating an <a> DOM object) is quick and dirty, but it works:
https://gist.github.com/jlong/2428561
Do use more stable library such as parseuri and URI.js for this task.

Related

JSON Deserializing in javascript

I have a json string like this
"{"value":"{\"success\":false,\"htmlCode\":\"Exists\",\"key\":\"xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb\"}"}"
I'm trying to deseriazlie this in javascript using following logic and trying to access one of the values in it.
obj = JSON.parse(data);
alert(obj.success);
But it fails all the time. I also tried doing
alert(obj.value.htmlCode);
alert(obj["value"].htmlCode);
alert(obj.value["htmlCode"]);
but nothing worked.
Can someone help please?
Please Remove Value From the JSON code
below is the updated JSON string
'{\"success\":false,\"htmlCode\":\"Exists\",\"key\":\"xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb\"}';
It will surely resolve your issue
Just make sure you escaped everything :
var value = "{\"value\":{\"success\":false,\"htmlCode\":\"Exists\",\"key\":\"xxxxxxxx-yyyy-zzzz-aaaa-bbbbbbbbbbbb\"}}";
console.log(JSON.parse(value));
Hope it helps

Find text in source code of page and create hyperlink

I need to use JavaScript to search the source code of the current page for a string, e.g data-userId="2008", then extracts the id number (2008 in this case) and creates a hyperlink to include it, e.g. http://www.google.com?2008.
I've been attempting to use indexOf and document.documentElement.innerHTML approaches but not getting anywhere. I've got closer with the help of this post but no success yet.
Here's what i have so far:
<script type="text/javascript">
function getVals() {
code = document.getElementsByTagName("html")[0].innerHTML;
results = code.match(/data-userId=(\d*)&/g);
for (i=0;i<results.length;i++) {
value = results[i].match(/data-userId=(\d*)&/);
}
}
onload = getVals;
document.write(code);
</script>
Due to restrictions on our network the solution needs to be JavaScript.
Use the getAttribute() method of the Element object http://www.w3schools.com/jsref/met_element_getattribute.asp.
I'm not sure why exactly you'd query the html element and then look at innerHTML. Do you not know which tags/selectors will contain the data attribute you're looking for? If you don't know which selectors you're looking for you can use a recursive function like this to walk the DOM and store the values in a data structure of your choice - I'll use an array of objects in this example (not sure how you need this data formatted).
Also, I'm not sure how you're choosing to visit these pages, but the below code could be easily modified to create hyperlinks when/if the attributes you're looking for are found.
var storeElements = [];
function walkTheDOM(node){
if(node.getAttribute('data-userId') !== null){
storeElements.push({"element": node, "attrValue": node.getAttribute('data-userId'});
}
node = node.firstChild;
while(node){
walkTheDOM(node);
node = node.nextSibling;
}
}
Then you can call the function like this:
walkTheDOM(document.querySelectorAll('html')[0]);
If this isn't what you're looking for let me know and I can change my answer. For those of you who've read Douglas Crockford's "Javascript: The Good Parts" this function may look very familiar :).

parse json object That stringify Twice

How can i parse some object that stringify twice?
Most of the time in my code it is not problem but some times it stringify twice, and I can not trace the code to find my problem.
My JSON object something like this:
""[{\"name\":\"trane\",\"price\":\"150000\",\"order\":\"\",\"sale\":\"\",\"printedPic\":\"\",\"remainingPic\":\"\",\"locationEncome\":\"\"}]""
It's definitely best to figure out where and why it's stringifying twice, but you can just parse twice if you have to.
JSON.parse(JSON.parse("JSON STRING HERE"))
Edit
Potentially you're stringifying an already stringified object, this could help you figure out what is going wrong.
Add this function to your code and then replace your JSON.stringify calls to JSON.stringifyIfObject calls. Just use this as a means of debugging though, I wouldn't put this into production.
JSON.stringifyIfObject = function stringifyIfObject(obj){
if(typeof obj == "object")
return JSON.stringify(obj);
else{
alert("found already stringified object")
return obj;
}
}
This post is a little bit old but I had the same problem today and it was caused by a third party library.
Javascript library Prototype.js applies JSON.stringify() twice when it is used in version 1.6.x (it seems that this bug was removed in version 1.7)
The following code :
var test = ["banana"];
JSON.stringify(test);
will give you the following result :
""[\"banana\"]""
instead of (normally expected) :
"["banana"]"
Here is my source :
https://github.com/krinkle/jquery-json/issues/35
If that happens to you, the best option is to upgrade that library if you can.

How to Split many Strings with Jquery

Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});

get query string into js/jquery

i hae a link like ( domain.com/jsapi?key=123456 )
hov can i get this "key" into my JS code? i use jQuery and i don't know about its are easy way to get this "key" into JS variable.
tanks for all.
This plugin might helps: jquery url parser
key = $.url.setUrl($(yourlink).attr('href')).param('key');
(not tested)
It's not jquery. It's pure javascript. You can use regexp.
str = "domain.com/jsapi?key=123456" # Take it from wherever you want
splitted = str.split(/\?key=([0-9]+)/)
Then you'll have an array in the "splitted" variable, it's second element (at the id 1) containing the value.
jQuery not needed. The query string is available from the DOM:
window.location.search.match(/key=([^&]*)/);
Which gives you an array that has your value in it.
You can use the URL constructor as follows:
let url = new URL('https://example.com/jsapi?key=123456');
console.log(url.searchParams.get('key')); // Outputs 123456
Using this method you can parse and get any part of a URL.
Important:
Note that I've added the protocol (https://) to the sample URL so I make sure it is a valid URL and it can be parsed.
Take into account the browser compatibility. You can check it here
For more details you can also the the specification.

Categories

Resources