my apologies if I used incorrect terms in my title. I am not sure how else to put this.
I am using Ajax to make a GET call and it responds with data in the form of html/txt/json etc. all in one file. I am trying to extract only whats in between [{ }].
I have successfully used the regex below to achieve this using https://regexr.com:
(?=\[\{).*(\}\])
On this response data returned by my GET call:
Lots of random text, random html, etc.
[{There is text in here hello world}]
Lots of random text, random html, etc.
As you can see this regex will properly extract this:
[{There is text in here hello world}]
This works great! But I just can't seem to figure out how to automatically parse the data after I get the response. I am currently trying:
$.ajax(settings).done(function (response) {
console.log(response.replace(/(?=\[\{).*(\}\])/));
});
But this isn't working. Am I going at this completely wrong? It's only outputting the full GET response and not the regex data. Any help is greatly appreciated.
If your response is a string, then you could use string.match() like this:
$.ajax(settings).done(function (response) {
console.log(response.match(/(?=\[\{).*(\}\])/));
});
You could try using the .indexOf() to find the indices of { and }:
var first_index = indexOf("{");
var second_index = indexOf("}"):
Once you find the indices, define a substring based on these indices:
var parsed_string = response.substring(first_index + 1, second_index);
You will need to add 1 to the first_index variable so that you do not get the "{" in the parsed_string variable.
jsfiddle
The more robust method would be to request the data in JSON, parse it accordingly then do javascript stuff with it:
var obj = JSON.parse(response);
// do js stuff with obj
This follows on from my question earlier about Visual Studio showing "" instead of ".
When I run the code below it creates a javascript array and returned as res[0] like below:
["Name","Name","Name"]
in visual studio it returns this:
"["Name","Name","Name"]"
When I run the code, this part shows the surrounding speech marks still (autocompletedata):
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );
This causes the code to not work. When i manually remove the surrounding double quotes, all works fine.
I've tried removing the start and end part of the string but it just removes the [ and ], which indicates that the string isn't surrounded by double quotes at all. I've also tried removing all double quotes but to no avail.
Can anyone explain whats going wrong?
var urlMethod = "/ajax.aspx/GetTeamMemberNamesList";
var params = new Object();
var result;
params.TeamID = 123;
result = SendAjaxSingleValue(urlMethod, params);
var res = result.d.split("|");
var autocompletedata = res[0];
autocompletedata.replace(/['"]+/g, '')
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );
To clarify the solution from the OP, the ajax call returns not the array itself but a JSON string, as is always the case when receiving data from a web server - hence why res[0] is returned as ["Name","Name","Name"].
Hence, in order to turn the response text into an actual array, it requires JSON.parse to perform the conversion.
Well, this was annoying - this fixed my issue:
autocomplete(document.getElementById("rd-search-form-input"), JSON.parse(autocompletedata));
[EDIT] I was modyfing the data later and it was reflected in the object when expanding it, I will accept my answer when I can.[/EDIT]
I've got a simple JSON string that needs parsing:
{"Points": [{"x": 0,"y": 33},{"x": 2200,"y": 28},{"x": 4400,"y": 23},{"x": 6600,"y": 20},{"x": 8800,"y": 19},{"x": 11000,"y": 18},{"x": 13200,"y": 17},{"x": 15400,"y": 15},{"x": 17600,"y": 13},{"x": 19800,"y": 12}]}
The string is generated by C++ code for graph drawing purposes. When I paste it into a json formatter it parses fine, giving proper values. The problem I'm facing are wierd Y values, for example the first object in array "Points" has y value of 20 - and there are no 20's anywhere in the string.
See attached picture, it explains everything. The code before what's on the picture is as follows:
RequestJSONParse: function(Data)
{
var Request = Data.split("|");
var RequestType = Request[0];
var RequestParams = Request[1];
var RequestData = undefined;
if (typeof Request[2] != "undefined" && Request[2] != "")
{
console.log("---");
console.log(Request[2]);
console.log("---");
RequestData = JSON.parse(Request[2]);
console.log("---");
console.log(RequestData);
console.log("---");
}
My question is - are the some special characters or a special way JSON.parse parses specifically x,y values? Or is this an encoding issue or something I can't even think of? I've been on this project for 2 years and didn't ever encounter anything like this and most of our UI is made by parsing JSON data.
Image explaining the problem
Check here your do like this
var json = "{\"Points\": [{\"x\": 0,\"y\": 33},{\"x\": 2200,\"y\": 28},{\"x\": 4400,\"y\": 23},{\"x\": 6600,\"y\": 20},{\"x\": 8800,\"y\": 19},{\"x\": 11000,\"y\": 18},{\"x\": 13200,\"y\": 17},{\"x\": 15400,\"y\": 15},{\"x\": 17600,\"y\": 13},{\"x\": 19800,\"y\": 12}]}";
var Request = json.split("|");
var data = JSON.parse(Request[0]);
console.log(data);
U can use above code if u r getting string in this way....
#JamesThorpe Was on point, I was modifying the object later and my changes were reflected in the object when it was expanded. The blue i symbol was the missing link for me.
I get the following when retrieving it.
var data = {"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}
If I check for typeof data I get a String back.
However, when I try to make a proper object out of it by replacing "%3A" with ":" etc the above object does not replace all occurrences but only the first.
data = data.replace(/\%3A/g,":") only replaces the first "%3A".
How can I make a proper object out of this with distinct_id, $initial_referrer as well as we $initial_referring_domain ?
Testing your code proves that your replace usage is actually okay, it indeed replaces all occurrences of %3A:
var data = '{"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}';
data = data.replace(/\%3A/g, ":");
alert(data);
However, regular expressions is not correct approach here, as you also have other encoded entities. Use decodeURIComponent function instead:
var data = '{"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}';
data = decodeURIComponent(data);
alert(data);
I want to parse this content using Javascript. The data looks like this:
{"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]}
Every single tutorial online teaches you how to parse JSON using Twitter, but I am not quite sure how parsing with JSON works.
I would like to set this up on a website to view the NFL team scores for a fun project and a good learning experience about parsing JSON, as I could care less about Twitter stuff.
Is this possible? Any good tutorials to start with? Even some starting code?
Generally speaking, you can use JSON.parse to do this. However, that snippet that you have does not appear to be strictly valid JSON (as seen here: http://jsfiddle.net/yK3Gf/ and also by validating the source JSON here: http://jsonlint.com/).
So you will either need to parse it by hand, or get nfl.com to fix up their JSON.
As an alternative, their JSON does parse successfully when using eval(), so you could parse it with something like:
var parsedData = eval('(' + jsonData + ')');
...as shown here: http://jsfiddle.net/yK3Gf/1/
Though be aware that parsing JSON in this way is generally frowned upon (particularly when the data being parsed is being delivered by a third-party source), as it leaves you open to XSS attacks should the data happen to include any executable code inside of it.
I am in a similar position - non javascript expert working on a fun project to familiarize myself with javascript, ajax, and json.
I took three different steps to handle the problem. I welcome any feedback on improving the solution.
The first step is to query the nfl site to pull down the scores. Because the source of the json, the nfl site, is different from your site, you will have to work around the javascript security constraints against cross domain querying. I found this stackoverflow link to be a good reference. I used JSONP for the workaround. I used http://whateverorigin.org/ as the indirection site.
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://www.nfl.com/liveupdate/scorestrip/scorestrip.json') + '&callback=?', handleQueryForScoresResult);
As others have pointed out, the nfl site returns invalid json data. The following sample line illustrates the problem:
["Sun","4:25","Final",,"TEN","7","MIN","30",,,"55571",,"REG5","2012"],
Notice the empty array element values (the repeated commas with no data in between). So in my json callback function, I corrected the data by adding empty strings (two double quotes) to repeated commas before calling jquery to parse the json data:
function handleQueryForScoresResult(data) {
var jsonStr = data.contents;
jsonStr = jsonStr.replace(/,,/g, ',"",');
jsonStr = jsonStr.replace(/,,/g, ',"",');
var scoresData = jQuery.parseJSON(jsonStr).ss;
.
.
.
}
Lastly, I created GameScores object to encapsulate the json data.
function GameScore(scoreData) {
this.scoreData = scoreData;
scoreData[2] = scoreData[2].toLowerCase();
scoreData[5] = parseInt(scoreData[5]);
scoreData[7] = parseInt(scoreData[7]);
}
function GameScore_getAwayTeam() { return this.scoreData[4]; }
function GameScore_getHomeTeam() { return this.scoreData[6]; }
function GameScore_isFinal() { return this.scoreData[2]=="final"; }
function GameScore_getHomeTeamScore() { return this.scoreData[7]; }
function GameScore_getAwayTeamScore() { return this.scoreData[5]; }
function GameScore_doesHomeTeamLead() { return this.scoreData[7]> this.scoreData[5]; }
function GameScore_doesAwayTeamLead() { return this.scoreData[5]> this.scoreData[7]; }
function GameScore_getWeekId() { return this.scoreData[12]; }
GameScore.prototype.getHomeTeam = GameScore_getHomeTeam;
GameScore.prototype.getAwayTeam = GameScore_getAwayTeam;
GameScore.prototype.isFinal = GameScore_isFinal;
GameScore.prototype.getHomeTeamScore = GameScore_getHomeTeamScore;
GameScore.prototype.getAwayTeamScore = GameScore_getAwayTeamScore;
GameScore.prototype.doesHomeTeamLead = GameScore_doesHomeTeamLead;
GameScore.prototype.doesAwayTeamLead = GameScore_doesAwayTeamLead;
GameScore.prototype.getWeekId = GameScore_getWeekId;
I only added a few accessors as I did not need most of the data. Your needs may vary.
We are using mootools for stuff like that, but you can do it it plain JavaScript as well: http://www.json.org/js.html.
Let's assume you already have a valid JSON String (jsonString) to parse. (If you don't know how to retrieve a String to parse using XMLHttpRequest from the given url you will have to look into that first.)
With plain JavaScript you will have to add Douglas Crockford's JSON library (or something similar) in order to provide a parsing Function if there is no native implementation:
var json = json_parse(jsonString) ;
link
With a JavaScript library like jQuery this would be
var json = $.parseJSON(jsonString) ;
Now, traversing the resultant JSON Object is a whole other issue, because you will have to know its structure before you can retrieve specific data.
In this particular case -- if it was indeed well formed -- you would have to do the following:
var data = json.ss ;
for(var i = 0 ; i < data.length ; i++) {
var entry = data[i] ;
var day = entry[0] ; //!! the Arrays seem to have a format where the first entry always contains the data and so forth...
/* ... */
// then do something with the data bits
}
Your main problem is that fact that the JSON your pulling in is malformed or not valid according to RFC 4627.
What you can do is grab the copy the JSON data and format it using this tool http://www.freeformatter.com/json-formatter.html
After you have the formatted version then you can use the jQuery ajax call
$.ajax({
url: "your-formatted.json",
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.ss.length; i++) {
document.write("Day: " + data.ss[i][0]);
document.write("<br/>");
document.write("Time: " + data.ss[i][1]);
document.write("<br/><br/>");
}
}
});
You shouldn't actually use document.write in your application. This is only for example purpose of displaying the data.
For this specific issue (the empty indexes within the arrays from the JSON response) I did a regex replacement with a lookahead assertion. Considering that request contains the XMLHttpRequest:
request.responseText.replace(/,(?=,)/gm, ",\"\"")
This will turn ,, into ,"", and will also work in case there are more commas in sequence, so ,,, becomes ,"","",. You can use JSON.parse() afterwards.
This malformed JSON can be parsed by the dirty-json NPM package (I am the author).
You can test a demo of the parser here: https://rmarcus.info/dirty-json
The parser interprets the JSON in your original question as equivalent to the following valid JSON:
{
"ss": [
[
"Thu",
"7:00",
"Final",
"BAL",
"19",
"ATL",
"20",
"56808",
"PRE4",
"2015"
],
[
"Thu",
"7:00",
"Final",
"NO",
"10",
"GB",
"38",
"56809",
"PRE4",
"2015"
]
]
}