I have a variable called "result",
var result;
that result value is equal to following value, please presume that is just a string :)
---------result value -----------
for (;;);{
"send":1,
"payload":{
"config":{
"website":"",
"title":"welcome to site",
"website-module":1313508674538,
"manufatureid":"id.249530475080015",
"tableid":"id.272772962740259",
"adminid":100002741928612,
"offline":null,
"adminemail":"admin#website.com",
"adminame":"George",
"tags":"web:design:template",
"source":"source:design:web",
"sitelog":[],
"errorlog":0,
"RespondActionlog":0,
"map":null
},
"imgupload":""
},
"criticalerror":[0],
"report":true
}
---------result value------------
From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.
How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.
You can simply evaluate the value of the variable to obtain the values. However, please note that your current value is not valid JSON; that for(;;); at the beginning of the value invalidates the format. Remove that, and you can do this:
var object = eval('(' + resultMinusThatForLoop + ')');
alert(object.payload.config.tableid);
If that data is a string the parse it with a JSON parse. The following should get the value you want
JSON.parse(result).payload.config.tableid; // "id.272772962740259"
Edit: though, as Tejs says, the for(;;) invalidates the string and stops it from being parsed. If you can remove that, do.
You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.
You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.
If result is a javascript object and not a string, you can just use 'result.payload.config.tableid'.
If it is not, how do you get the AJAX result? Are you using XmlHttpRequest directly? Most libraries will give you a javascript object, you might be missing a flag or not sending the response back with the right content type.
If it is a string and you want to parse it manually, you should use a JSON parser. Newer browsers have one built in as window.JSON, but there is open source code for parsing it as well.
var obj = JSON.parse(result);
alert('tableid is ' + obj.payload.config.tableid);
Related
Something so trivial and I just can't seem to find an answer.
This is my code so far. However this is with the JSON alredy set as a variable.
I need it so that it gets the JSON text from
http://localhost:3001/sync/
and makes it equal to var txt. INSTEAD of the var txt = I want it so get the JSON text from the URL INSTEAD of the text I've added.
var txt = '{"loading":false,"playing":true,"position":0,"duration":389492,"index":13,"repeat":false,"shuffle":false,"volume":0.337499052286148,"context":{"uri":"spotify:user:#:playlist:66HXOPaG8wwe7k8t4YZj5b"},"contexts":[{"index":13,"descriptor":{"type":"list","uri":"spotify:user:#:playlist:66HXOPaG8wwe7k8t4YZj5b"}}],"track":{"artists":[{"image":"spotify:image:15a09a886f2149909821763f2f074cf1b7975574","images":[[64,"spotify:image:1aa2b5417668fdfc6966c9745b437e587d7ff23f"],[300,"spotify:image:15a09a886f2149909821763f2f074cf1b7975574"],[600,"spotify:image:865b8c83601ce2aef204a9c071fd2f531c12c000"],[1000,"spotify:image:5311029c2ba3de0b4e5d117b4e90d57b60720902"]],"name":"Duke Dumont","uri":"spotify:artist:61lyPtntblHJvA7FMMhi7E"}],"disc":1,"duration":389000,"image":"spotify:image:6f592ef177e159c00dd4f08049c4c962466b0776","images":[[64,"spotify:image:68fd12e77d374e7b9618ca0cf6786b9479837175"],[300,"spotify:image:6f592ef177e159c00dd4f08049c4c962466b0776"],[600,"spotify:image:6a30d6808f92167b4cb10eed2cf5f9838442d591"]],"name":"The Giver - Original Mix","number":2,"playable":true,"popularity":64,"starred":false,"explicit":false,"availability":"premium","album":{"uri":"spotify:album:66Io82H9e3b2rrtHFs2sE0"},"local":false,"advertisement":false,"placeholder":false,"uri":"spotify:track:6GbLDdBuFxZLDHhluGrrmA"}}';
var obj = eval ("(" + txt + ")");
document.getElementById("demo").innerHTML =
obj.playing;
It looks like you need to do use xmlhttprequest (ie. ajax). It is used to retrieve data from urls asynchronously.
You can either follow a tutorial to learn how to use it. Or you could learn how to use jquery (specifically jquery.get).
I'd suggest that if you don't know either, you either way start learning about xmlhttprequest but end up using jquery anyway.
And as the other post mentioned, once you learn how to retrieve data, use JSON.parse to parse the text to json, even though jquery can handle that automatically, too.
As far as I understand, u want the data to come from the URL and get assigned to variable txt.
In tat case you need to make a ajax call like this using jquery.
$.ajax({
url:"http://localhost:3001/sync/",
success:function(result){
var txt = result;
}});
U can now use JSON.parse(txt) to parse the json.
I am being sent an ill formed JSON string from a third party. I tried using JSON.parse(str) to parse it into a JavaScript object but it of course failed.
The reason being is that the keys are not strings:
{min: 100}
As opposed to valid JSON string (which parses just fine):
{"min": 100}
I need to accept the ill formed string for now. I imagine forgetting to properly quote keys is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? For now I may have to parse character by character and try and form an object, which sounds awful.
Ideas?
You could just eval, but that would be bad security practice if you don't trust the source. Better solution would be to either modify the string manually to quote the keys or use a tool someone else has written that does this for you (check out https://github.com/daepark/JSOL written by daepark).
I did this just recently, using Uglifyjs to evaluate:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "var myobject = " + badJSONobject;
var ast = jsp.parse(orig_code); // parse code and get the initial AST
var final_code = pro.gen_code(ast); // regenerate code
$('head').append('<script>' + final_code + '; console.log(JSON.stringify(myobject));</script>');
This is really sloppy in a way, and has all the same problems as an eval() based solution, but if you just need to parse/reformat the data one time, then the above should get you a clean JSON copy of the JS object.
Depending on what else is in the JSON, you could simply do a string replace and replace '{' with '{"' and ':' with '":'.
First of all, I'm fairly new to json, so please forgive me if I've made a terrible mistake. I've got some code that gets a json object from a website using YQL It returns it as a string. So now I want to parse this into a json object and than read it.
This is my code:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%22http://iphone-api.uitzendinggemist.nl/v1/episodes.json%22%20and%20xpath=%27*%27&format=json", function(data) {
console.log(data);
content = data.query.results.html.body.p;
json = JSON.stringify(eval("(" + content + ")"));
str = json.revoked;
$('#table').append('<li>' + str + '</li>');
});
JS fiddle
I just can't figure out why this gives me undifined, instead of the value it should give.
So now my question was if someone here knows why it isn't working properly.
The json variable is an array, you need to access an index.
string = json[0].revoked;
You have many many many errors in your code. You should try to understand each step that you are doing, it looks like you don't. Here's a fork of your code that does something, I'm not sure what you want it to do. I'll tell you few things you did wrong:
Use var keyword when declaring new variables within functions
Don't parse JSON using eval(), but use some parser. E.g. $.parseJSON(). Using eval() is a security risk, as returned script WILL be executed on client and you should only be interested in getting data.
When constructing HTML, take care to encode text that you want displayed. In your case, don't concatenate strings ('<li>' + str + '</li>'). You can use jQuery ($('<li>').text(str)).
Don't add li elements to a table element. Either add them to ul or ol elements, or in case of tables create rows and cells.
It is completely unclear why you would eval, and them stringify an object. You end up with same exact data.
I have a .html file and want to show only 1 object value. The html file doesnt have any tag because its reading data database and only have simple format.
SPractice=0&SLive=0&OnlineU=349
Is there any way to read only value of OnlineU? Is there any way to get this value using javascript or classic asp?
That's not HTML. Nor is it XML or JSON, so you have to use a customer parser on the server or the client.
From parsing a similar format in JavaScript, I know you can it with regex. However, the corner cases are tricky if the values can have special characters e.g. an escaped equal sign). Look at split, and be sure to use a cross-browser split method like this.
Is that what you need?
var s='SPractice=0&SLive=0&OnlineU=349';
eval (s.replace(/&/g,';'));
alert(OnlineU);
Check out the jQuery BBQ plugin:
http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html#jQuery.deparam
you can use it like this:
var string = "SPractice=0&SLive=0&OnlineU=349";
$(function() {
alert($.deparam(string, true)['OnlineU']); //alerts 349
});
It covers pretty much every corner case.
EDIT: Since you are already using jQuery try this.
$.get('test.html', function(data) {
alert('Raw data: ' + data); //Should alert the raw data
var onlineu = $.deparam(string, true)['OnlineU'];
alert('OnlineU: ' + onlineu); //Should alert 349 or something like that.
}, dataType: 'text');
I trying to build a JavaScript function which will grab a JSON encoded array and return a value based on the requested key. I use the jQuery $.parseJSON() method to take the JSON string and convert it into a JavaScript object. Here a watered down example:
function getValue(dynamicArrayKey) {
var theArray = $.parseJSON(/* Get some JSON from a source using jQuery */);
alert('Here is the value: ' + theArray.dynamicArrayKey);
}
So the key I want will be given to the function, and it should return the resulting value. I am thinking that the JavaScript eval() method should be used in there somewhere, but I'm not sure. Any help would be greatly appreciated.
There's no need to eval(), use
alert('Here is the value: ' + theArray[dynamicArrayKey]);
Take a look at this. It may help.
How to search JSON tree with jQuery