I am reading the plain text file in node.js using ajax call from client side.
Result :
success gives the result as below.
""[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n""
After parsing the above result :
JSON.parse(result);
"[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] [{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}] "
I want to change this string to array of objects,
Expected Result is array of objects:
[{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6},
{"x":233,"y":279,"count":1},{"x":256,"y":243,"count":6}
]
Ajax call Code
$.ajax({
url: document.URL + "getData",
method : "GET",
success: function (result) {
var info = JSON.parse(result);
var object = JSON.parse(info);
console.log(object);
}
});
Any idea will be helpful.
That is some seriously messed-up JSON. There's an extra quote mark at each end, and ]\n[ in the middle where there should be a ,.
You really should fix your server to generate valid JSON, but if you can't, you could tweak it like this:
var res = '"[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"';
var resfix = res.replace( /^"|"$/g, '' ).replace( ']\n[', ',' );
JSON.parse( resfix );
I changed the extra set of quotes at the very outside of your var res = string to make it a valid JavaScript string for testing.
It looks to me like you've simply got double-encoded JSON. Just run it through JSON.parse() a second time.
EDIT actually, that's not quite right - the output contains two JS arrays, with a \n separator and no enclosing array. You will have to manipulate the data a bit (looking at that now) to make it parseable a second time.
EDIT2 This appears to work, albeit that your current var res line includes an extra pair of surrounding quotes that aren't legal so in this test I've removed them:
var res = "[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n[{\"x\":233,\"y\":279,\"count\":1},{\"x\":256,\"y\":243,\"count\":6}]\n"
var out = JSON.parse(res.replace(/]\s*\[/g, ','));
Related
I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.
I am looking for an easy way to trim left side from my json response and trim right side from my json output.
An example my json how it is:
{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}
How i want it to be:
[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]
As you can see I wat TrimLeft all before [ and TrimRight alls behing ] and this is where I have my json response in:
function responseHandler(res) {
return res;
}
The easiest way to go would probably to just save this json to a variable and access the content of something similar like this:
var jsonOutput = {"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var something = jsonOutput.something;
console.log(something);
The output should be the expected json.
Edit 1
Referring to your edit I add another piece of code to come up to your solution.
function responseHandler(response) {
var result = response.something;
return result ;
}
This should give you the expected response.
Why would you want to to that? You can access everything in that json respone. However you can just use javascript string functions, for example:
var x = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},
{"id":"3","name":"Test3"}]}';
y = x.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
console.log(y);
if you your ({"something":) this content is fixed you can use below code.
<script>
var str = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}';
str = str.substring(0, str.length - 1).replace('{"something":','');
console.log(str);
</script>
var obj={"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var str=String(obj);
var output=str.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
JSON.parse(output);
The String() function converts the value of an object to a string.
The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value, starting the
search at fromIndex. Returns -1 if the value is not found.
The lastIndexOf() method returns the index within the calling String
object of the last occurrence of the specified value, searching
backwards from fromIndex. Returns -1 if the value is not found.
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.
I have some output data from an ajax call and I would like to take out the last 8 characters of the data but also delete them out of that string that when I print out the data, the string I have taken would not show up.
Here is the code I have tried, It successfully takes that last 8 characters but does not remove them.
var data = "This is some data 12345678";
var comment_id = data.slice(-8);
jQuery.trim(comment_id);
$('#comments_'+comment_id).html(data);
var comment_id = data.slice(-8);
this line will not change the value of data it will only take out last 8 characters from the data. data is a string and it is immutable
add the following line after this line
data = data.substring(0, data.length -8);
Return json from server side code
{message:"This is some data",comment_id:"12345678"}
You can access it like
$('#comments_'+data.comment_id).html(data.message);
Why not substring?
var strLen=data.length,
comment_id=data.substring((strLen>=8?strLen-8:0),strLen);
(ignore this part of my answer)
To remove them, do almost the same:
data=data.substring(0,strLen-8)
Equivalent of:
"daddaddad" to "d"
(I didn't note you was wanting that, so I'm sorry)
Here's a nice approach using regex that's a bit cleaner too:
var data = "This is some data 12345678",
comment_id = data.match(/\d{8}$/)[0];
data = data.replace(comment_id, '').trim();
$('#comments_' + comment_id).html(data);
When placing the "key" variable inside of this string, it displays 'simplelogin%3A5' instead of 'simplelogin:5'. Is there a way to just pass in the latter?
var populateTasks = function(date, key){
$scope.ref = new Firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks");
};
results in: https://myfirebase.firebaseio.com/users/simplelogin%3A5/tasks
I need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks
var uri = "//what you need to convert";
var uri_dec = decodeURIComponent(uri);
var res = uri_dec;
Where does the value of key come from? If you get it from a URL, it makes sense that you see %3A.
A : has a special meaning in a URL, so it is escaped. And the URL escape sequence for a : is %3A.
To convert the %3A back to : you simply unescape it like this:
unescape(key)
Or use decodeURIComponent, which in this case accomplishes the same. The best way to decode the value depends on why it was encoded in the first place, hence my initial question.
Have you tried trimming key before concatenating it to the URL?
key = key.trim();
Here is the JSON returned from my Server.
"[{"description":"A user","name":"test","type":"user"}]"
I want to remove the outer double quates. Which means I want the JSON as
[{"description":"A user","name":"test","type":"user"}]
How can I do this? Please help.
You want to turn the JSON into JS objects right? If so, you would do JSON.parse(json). If you need IE7 support, you have to include a polyfill for JSON as it's not supported in IE7<.
You can get the current JSON polyfill here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
As the response from the server is not valid JSON you have to request it as text, fix it, and parse it as JSON. Use dataType: 'text' in your options in the ajax call.
Use the substr method to cut of the first and last character:
data = data.substr(1, data.length - 2);
Then you can parse the JSON:
var obj = $.parseJSON(data);
To strip the first and last character from a string:
var fixed_string = string.substring(1, string.length - 1);
var str = '[{"description":"A user","name":"test","type":"user"}]';
var data = (new Function( "return " +s))();
console.log(f);
In your case response from server is a json string you have to convert it to json object
var str = '[{"description":"A user","name":"test","type":"user"}]';
str = eval('('+str+')');
console.log(str[0].name) //this will give test
Hope this helps.