Link to home
Start Free TrialLog in
Avatar of rajan416
rajan416

asked on

How to get convert json array to comma separated values

I would like to convert the following json array to  comma separated values

i/p:

[{"filter":"ID","filterValues":["050886","050885","050884","050883","050882"]}]

expected o/p;
String field="ID"
String values= "050886","050885","050884","050883","050882";

I tried the below code , but  I am getting exception  while getting filter values. Any help would be appreciated.
String input ='[{"filter":"ID","filterValues":["050886","050885","050884","050883","050882"]}]';
JSONArray jsonarray = (JSONArray) new JSONTokener(input ).nextValue();
	
			for (int i = 0; i < jsonarray.length(); i++) {
					JSONObject jsonobject = jsonarray.getJSONObject(i);
					String field= jsonobject.getString("filter");
                                        String values= jsonobject.getString("filterValues");
			}

Open in new window

Avatar of Tomas Helgi Johannsson
Tomas Helgi Johannsson
Flag of Iceland image

HI!

What exception do you get and what JSONTokener are you using ?
http://www.massapi.com/class/js/JSONTokener-1.html#Example6

And I believe this should work

String input ='[{"filter":"ID","filterValues":["050886","050885","050884","050883","050882"]}]';
JSONArray jsonarray = (JSONArray) new JSONTokener(input ).nextValue();
	
			for (int i = 0; i < jsonarray.length(); i++) {
					JSONObject jsonobject = jsonarray.getJSONObject(i);
					String field= jsonobject.getString("filter");
                                        String values= jsonobject.getJSONObject("filterValues");
			}

Open in new window


Regards,
     Tomas Helgi
Avatar of rajan416
rajan416

ASKER

Hi,

The getJSONObject  throws compile time error for converting to string...

I tried jsonobject.getJSONArray("filterValues").toString(); and got  ["050886","050885","050884","050883","050882"]. How can i convert this to below format

 "050886,050885,050884,050883,050882"
ASKER CERTIFIED SOLUTION
Avatar of Tomas Helgi Johannsson
Tomas Helgi Johannsson
Flag of Iceland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is not working....
I'm getting the following output:

050886,050885,050884,050883,050882

what are you getting?
This is perfect...Thank you guys...
Although, it won't give you the quotes around each of the filter values.
Guyz, Dont struggle that much ,,,here is the best way I have:

    var distStateIds = [];
     var stateIds = distStateIds.map(function (val) {
            return val;
        }).join(',');