How to convert the json results to array using javascript? - javascript

I need to convert the Json response to array using JavaScript .
I have the json response which is :
["simmakkal madurai","goripalayam madurai"].
now I want to change this results to array format .
So, How to I convert the json result to array.

Try this :-
var obj = $.parseJSON('["simmakkal madurai","goripalayam madurai"]');
If you alert(obj[0]), you will get answer as simmakkal madurai

var arr = JSON.parse('["simmakkal madurai","goripalayam madurai"]');

Yeah,
if your response is
var res = '["simmakkal madurai","goripalayam madurai"]';
Then you just need to do
var arr = JSON.parse(res);
Alternativly you could do an eval but evals are never realy recommended, but since you are going from server side to client side (php -> javascript) it wouldnt the the worst thing.
Anyways JSON.parse should work

Related

Remove multiple square brackets using replace() - javascript

I have a response from the server that is like this:
users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
It's a string not an array like it appear, since I need an array to work on, how I can remove the square backets and then the commas to obtain a normal array?
I've tried in this way:
var data = ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
data.replace('[', '').replace(']', '').split(',');
but chaining two .replace() functions and a split() isn't the best solution. Can anyone halp me?
In your example data is an array.
However, if data was a string you would convert it to an array like this:
var arr = JSON.parse(data);
In short,
Here you have provided data in normal string formate not in JSON string formate
var data = 'users: ["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]'
var squareBracketData = data.substr(data.indexOf("["))
var array = JSON.parse(squareBracketData)
console.log(array)
Some personal advice, Try to send JSON stringify data from the
server so it will make your life easy
Example:
var users =["beautykarttworld","sbdanwar","haiirfavs","show__tanz","kinjal_suhagiya_9999","_adultmafia_"]
// Stringify data
var data = JSON.stringify({users})
console.log("Data")
console.log(data)
// retrieve data from string
var parsedData = JSON.parse(data)
var parsedUsers = parsedData.users
console.log("parsedUsers")
console.log(parsedUsers)

Conversion of string to list from a file

I have a file in which the data(list) looks something like this
[5,[5,[5,100,-200],200,-400],300,-500]
Now when I read this file in an angular application, the file contents would be converted to string and hence would return a string object which would look something like this
"[5,[5,[5,100,-200],200,-400],300,-500]"
Is there a way where I can convert this back to the list in which it was originally present?
There is one approach but the solution is for a different problem. If my file has data
200
300
400
500
Then I can split this string by using
var newData = fileContent.split('\n');
desiredList = []
for(var z=0;z<newData.length;z++){
desiredList.push(parseInt(newData[z]))
}
The desired list would give me a list which I wanted. But for the question which I asked is there any approach?
JSON.parse("[5,[5,[5,100,-200],200,-400],300,-500]") should convert it to JavaScript object.
You can use eval()
var str = "[5,[5,[5,100,-200],200,-400],300,-500]";
var jsonArr = eval(str);
console.log(jsonArr);

javascript get nested array elements

in javascript how do I get individual elements out of this array?
http://pastebin.com/n8yrnCpf
I need to loop through it and format the data
how would I get array[0][1][1], for instance
and perhaps there is some json script for doing it quickly
Json comes from J ava S cript O bject N otation. It's a javascript-compatible format, so you can loop through it, and access it as you need. In other words, you do can get array[0][1][1].
If what you're asking for is how can you receive a JSON in a string and convert it to an "usable" JavaScript variable, you can do that this way:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = JSON.parse (json_string)
console.log (parsed_json[0][0])
Or, if you use old browsers (IE7 and so), you can use JQuery and its elder-safe function parseJSON:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = $.parseJSON (json_string)
console.log (parsed_json[0][0])

create javascript array in json response in Java

I have a servlet where I send JSON response (back to javascript) . For example , my response looks like
{
"responseStr":"1,5,119.8406677,7,7,116.5664291,10,10,116.6099319,20,10,117.2185898,25,3,115.2636185"
}
Now what is happening at the moment is that I am collecting data( numbers above) in servlet and sending it in JSON response as a String with comma separated values. When this response reaches front end, all these numbers have to go in a javascript array (where I do my further logic). Currently I am doing this by
var res = JSON.parse(REQ.responseText);
var myArr = res.responseStr.split(',');
My thinking is that the second line( where I use split()) is causing a bottleneck in my application . A few data points as in above example are not a trouble but it becomes a problem when i have thousands of data points.
So my question is that is there a way that when I am creating my response in servlet that I can create the response as javascript array so that I do not have to use split() at all?
Any better ways of achieving the above task of converting the response into javascript array?
If you send responseStr as an Array, when the JSON parses it, it will be an array. So you could send your JSON response as "[1,2,3,4,5,6,7]" and so one, and when you JSON.parse, it will return an array.
To make it a little more clear :
var arr = [1,2,3,4,5];
arr = JSON.stringify(arr); // "[1,2,3,4,5]" -- String
arr = JSON.parse(arr); // [1,2,3,4,5] -- Array
In your response set content-type JSON/application and send JSON array
{
"responseStr":["1","5","119.8406677","7","7","116.5664291","10","10","116.6099319","20","10","117.2185898","25","3","115.2636185"]
}
Then in your JavaScript you can simply use (reference):
var myArray = responseJSONObject.responseStr;
You may utilize JSON.js for various tasks.
That is a great question. JSON can return an array as simply as
{ "responseStr": [[1], [2], [3], [4] }
Cool!
Double Quotes are not necessary unless you want them as strings.
One more thing, you can have multi dimensional arrays too!
{ "responseStr": [[1,10], [2,20], [3,30], [4,40]] }
This link is a great reference:
http://json.org/fatfree.html

javascript split and JSON.parse

I want to parse array in JSON format using javascript. I have written following code.
var data = "abc, xyz, pqr";
var data_array = data.split(',');
var data_parsed = JSON.parse(data_array);
alert(data_parsed);
It gives me the error of JSON.parse
I have no idea how to resolve this javascript error.
You don't have any JSON, so don't use JSON.parse. Once you split you already have an array whose elements could be used directly:
var data = "abc, xyz, pqr";
var data_array = data.split(',');
alert(data_array[0]);
and if you want to convert this array to a JSON string you could do this:
var json = JSON.stringify(data_array);
alert(json);
That's because "abc, xyz, pqr" isn't valid JSON. Plus, JSON.parse() is meant to parse JSON strings, not arrays. What are you trying to do, perhaps we can better assist.
This is actually a convenient short cut to json processing if you only need a smaller set of variables.
PHP:
return $var1 .','. $var2 .',some_string_value.';
Javascript:
var myReturnArray = returnValue.split(',');

Categories

Resources