JSON Deserializing in javascript - 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

Related

Why use JSON.parse(decodeURIComponent(staticString))?

Certain dynamic web frameworks use this code fragment
<script>
appSettings = JSON.parse(
decodeURIComponent(
"%7B%22setting1%22%3A%22foo%22%2C%22setting2%22%3A123%7D"));
</script>
Is there a standard HTML5/JavaScript problem are they trying to solve with this code. Why not just
<script>
appSettings = {"setting1":"foo","setting2":123};
</script>
Note: this is dynamically generated code. I'm assuming on the server they are doing something like
var settingsString = encodeURIComponent(JSON.stringify(settings));
var output = '<script>appSettings=JSON.parse(decodeURIComponent("' +
settingsString +
'"));</script>';
But it seems like it would work just as well like this
var settingsString = JSON.stringify(settings);
var output = '<script>appSettings=' +
settingsString +
';</script>';
One idea is the latter could contain code but they are the ones providing the string, it's not user data so they're no chance it could be code. Plus using JSON.stringify on the server would remove all code. On the client even then a simple JSON.parse of a JSON.stringifyied object would prevent code.
Is there a concrete problem being solved by the triple parsing? Once by JavaScript, once by decodeURIComponent, once by JSON.parse?
THIS IS NOT AN OPINION BASED QUESTION
The question is what problem is being solved. Either there is a problem being solved or there is not. No opinions required to answer that question. For example if JSON.stringify happens to emit unparseable code sometimes (which as far I know it doesn't but if someone knows better then that would be a good answer as to why).
Also note: I'm not asking why their framework does this. I'm asking if there is real problem being solved in standard HTML5/JavaScript. In other words, should I adopt this pattern because I'm going to run into an issue someday if I don't.
Is there a concrete problem being solved by the triple parsing?
Yes. Your suggested solution has two problems:
It's parsed as HTML. Things like </script> can cause havoc in an inline script.
It's parsed as JS. Not all JSON strings are valid JS literals.
The decodeURIComponent + JSON.parse approach is a crude workaround however and looks more like a quick fix than a proper solution.
#katspaugh is correct
Testing
var settingString = JSON.stringify({
"</script>": "<script>bar=123</script>",
});
Generates the code for the above example as
<script>
appSettings = {"</script>":"<script>window.bar=123</script>"}
</script>
Which fails to parse as HTML. Adding the encodeURIComponent on the server JSON.parse(decodeURIComponent(...)) on the client fixes that issue
DO NOT USE IT.
let str = `C:\\Users\\Administrator\\Desktop\\小灶\\GT4T_translated_Chinese Simplified (简体中文)\\2013\%2F193461.pdf`
let newStr = decodeURIComponent(JSON.parse(`"${str}"`))
Depending on the str content, you may get unexpected errors. The code above will cause this error:
SyntaxError: Unexpected token U in JSON at position 4

Pass object to html String

I am in a situation here, i think its a simple one but i can't sort it out.
I Have a HTML element where i should pass a json Object
code
var x = "<li id='tag_1'></li>"
var obj = {"name":"krishna","id":"krish1"}
when I convert this to html i want to get Like this
<li id="tag_1" data-options={obj}></li>
I tried $(x).data("options",{obj}),
tried to pass as a string when creating the html element,but did'nt work
Thanks
$(x).data("options",{obj}) is a perfectly good way to do it, provided you fix the syntax error. Just pass obj directly, and jQuery will save it as an object. It will not, however, be added as an attribute.
$(x).data("options",obj)
If you look at the documentation for .data() it specifies that your value doesn't have to be a string:
value
Type: Anything
The new data value; this can be any Javascript type except undefined.
Try $(x).attr("data-options",JSON.stringify(obj))
If you don't want it printed in your HTML use $(x).data("options",obj)

Converting a query url to a json

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.

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];
});

Javascript json, check all keys for undefined ('null') and set default

Firstoff I'd like to add I've been learning javascript for like only 2 days now. I'm pretty much way ahead of myself with what I'm trying to get but here goes.
I have a json array from which I get data to replace/insert in my page. The first problem I have is that if it comes across an empty ('null') key it will just stop. Will not even try to continu.
document.getElementById("id1")src=json.img1.link;
document.getElementById("id2")src=json.img2.link;
document.getElementById("id3")src=json.img3.link;
json.img2.link is empty ('null' response from json.). javascript will then not replace "id2" but it also won't replace "id3".
I'm now trying to find a solution where it will if nothing else at least set a default.
The script is not continuing executing because it comes to an error --trying to access property link of an undefined object
Try
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
This way your are checking for undefined (ie null) object in img2 and assigning the default value. This assumes that what is not defined (null) is the img2 object.
Actually I don't think your code should work at all, you are missing the. before the src So, try
document.getElementById("id1").src=json.img1.link;
document.getElementById("id2").src=json.img2.link;
document.getElementById("id3").src=json.img3.link;
and let us know if that doesn't solve the problem.
Btw, +points for learning JavaScript and not just straight into jQuery!

Categories

Resources