This looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
Answer from gen_Eric on Stack OverflowThis looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
var text = "";
for(var i=0; category.length; i++)
{
text += category[i].name;
if(i!=category.length-1)
text += ", ";
}
text processing - How to combine strings from JSON values, keeping only part of the string? - Unix & Linux Stack Exchange
How to concatenate json or string outputs from two nodes
How to concatenate JSON data into string?
mysql - Join all JSON object string values - Stack Overflow
If i understood correctly, you can do the following:
var json= {"Title":"Movie1","Year":"2013"};
var result="";
for( key in json){
result+= json[key];
}
You don't have to know the number of properties or it's names before hand. This should work for simple scenarios.
Demo try this,
var json= {"Title":"Movie1","Year":"2013"};
var append="";
$.each(json,function(key,value){
append+=value;
});
It sounds like your @RemoteAction should return multiple addresses where each address looks like "city, postcode, citycode". For that to work I would expect that the JSON returned would be an array of the objects you post in the question not a single object.
The easiest way to parse such a structure is to submit an example of it to JSON2Apex and use the code that is generated.
The return type of your @RemoteAction method remains List<String> but each item in the list is:
calOut.add(p.city + ', ' + p.postcode + ', ' + p.citycode);
assuming p is a reference to the properties field of one of the returned and parsed objects.
PS
The names here depend on what the JSON fields are called but the code would look something like this:
List<String> calOut = new List<String>();
JSON2Apex parsed = JSON2Apex.parse(res.getBody());
for (JSON2Apex.Feature f : parsed.feature) {
JSON2Apex.Properties p = f.properties;
calOut.add(p.city + ', ' + p.postcode + ', ' + p.citycode);
}
return calOut;
Change the static method return type to string from the List<String> and
return the calOut list variable as
@RemoteAction
global static List<String> restapi(string accName)
{
string jsonStr;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + accName+ '');
req.setHeader('Accept','application/JSON');
req.setMethod('GET');
HttpResponse res = h.send(req);
system.debug('res.getBody()===>'+res.getBody().replace('\n', ''));
List<String> calOut = new List<String>();
List<String> finalcalOut = new List<String>();
jsonStr= res.getBody();
JSONParser parser = JSON.createParser(jsonStr);
while (parser.nextToken() != null)
{
if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
{
String fieldName = parser.getText();
if(fieldName == 'label')
{
parser.nextToken();
calOut.add(parser.getText());
}
if(fieldName == 'context')
{
parser.nextToken();
calOut.add(parser.getText());
}
if(fieldName == 'city')
{
system.debug('city ---->'+parser.getText());
parser.nextToken();
calOut.add(parser.getText());
}
}
finalcalOut.add( String.join(calOut,', '); );
}
return finalcalOut;
}
}
You would be getting something like
51, Marren, Champagne-Ardenne, Sezanne, 51120
Note JSON stands for JavaScript Object Notation. JSON is always a string. It is a string representation of your encoded data. There is no such thing as "a JSON Object".
Don't attempt to write JSON by joining strings and other values together. Instead build an object and pass it to JSON.stringify -
const dept = "sci"
const avg = 77.09
// make an object
const myobject = { courses_dept: dept, courses_average: avg }
// use JSON.stringify to encode myobject to JSON
const myjson = JSON.stringify(myobject)
console.log("encoded", myjson)
// test JSON.parse to decode the JSON and get the object back
console.log("decoded", JSON.parse(myjson))
encoded {"courses_dept":"sci","courses_average":77.09}
decoded {
"courses_dept": "sci",
"courses_average": 77.09
}
If you want to use strings:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that dept is a string. If you don't know this in advance, wrap each variable with JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
You can also just do a regular object:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)