This will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
Answer from joeltine on Stack OverflowThis will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.
Videos
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
Considering you use a Json.net library, I suggest first to split your string to an array by comma andserialize it to a string:
var ids = "100,140".Split(',');
var personsString = JsonConvert.SerializeObject(new { person = ids.Select(x => new { id = x }).ToList()});
In my example, i serialize a dynamic type, but you can implement your custom class Person with ids array.
first split your string and store in an array. Then convert your strings to jsonObjects. Add jsonobjects to jsonarray. follow the below code . it's working.
String split = "100,140";
String[] datas = split.split(",");
JsonArray jsonArry = new JsonArray();
for (String data : datas)
{
JsonObject jsonobj = new JsonObject();
jsonobj.addProperty("id",data);
//jsonobj.SetNamedValue("id", JsonValue.CreateStringValue(data));
jsonArry.add(jsonobj);
}
JsonObject jsonobj2 = new JsonObject();
//jsonobj2.SetNamedValue("person", jsonArry);
jsonobj2.addProperty("person", jsonArry);
//also you can convert the jsonobject to string.
String jsonString = jsonobj2.ToString();
For such a trivial example, it's pretty easy to produce a poorly-formed JSON String of your content and let JSONObject patch it up.
In a single expression:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$)", "$1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}
If you really want to keep the 0.0 as Strings:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$)", "$1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}
If you want to account for possible extraneous whitespaces:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|$)", "$1:$2,")))
.. will work with inputs like "art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0" and other cases.
Disclaimer: it's not crazy-sexy code but drop in a one-line comment and it could be reasonable so long as the data structure stays simplistic.
You should use Map instead of Array (List of key/value pair is Map, not Array).
1 way: Using JsonObject
String [] arrayStr=strVal.split(",");
JsonObjectBuilder builder = Json.createObjectBuilder()
String key = null;
for (String s: arrayStr){
if(key == null) {
key = s;
} else {
builder.add(key, s);
key = null;
}
}
JsonObject value = builder.build();
2 way: Using Map
String [] arrayStr=strVal.split(",");
Map<String,String> map = new HashMap<>();
String key = null;
for (String s: arrayStr){
if(key == null) {
key = s;
} else {
map.put(key, s);
key = null;
}
}
// convert Map to Json using any Json lib (Gson, Jackson and so on)
You can do the following,
data = [
{'id': 1,
'name': 'book',
'colors': 'red, yellow, blue'
},
{'id': 2,
'name': 'book',
'colors': 'red, yellow, blue'
}
];
ret = data.map((item) => {
return {...item, colors: item.colors.split(',').map(item => item.trim())};
})
console.log(ret);
Strings get into arrays in each object.
let arr = [
{id: 1,
name: 'book',
colors: 'red, yellow, blue'
},
{id: 2,
name: 'book',
colors: 'red, yellow, blue'
}
]
for (let index in arr) {
let colorsIntoArr = arr[index].colors.split(',');
arr[index].colors = colorsIntoArr;
}
/*
[
{
"id": 1,
"name": "book",
"colors": [
"red",
" yellow",
" blue"
]
},
{
"id": 2,
"name": "book",
"colors": [
"red",
" yellow",
" blue"
]
}
]
*/
console.log(arr)
This can be achieved via the join() method which is built into the Array type:
const object = {
"id" : "122223232244",
"title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ",
"data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]
}
/* Join elements of data array in object to a comma separated string */
const value = object.data.join();
console.log(value);
If no separator argument is supplied, then the join() method will default to use a comma separator by default.
Update
If the JSON was supplied in raw text via a string you can use the JSON.parse() method to extract an object from the JSON string value as a first step like so:
const json = `{"id" : "122223232244","title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ","data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]}`
/* Parse input JSON string */
const object = JSON.parse(json);
/* Join elements of data array in object to a comma separated string */
const value = object.data.join();
console.log(value);
Access object properties using dot notation (e.g. obj.data) and then on the array you can use join to convert to a string with a comma in between.
const obj = {
"id" : "122223232244",
"title" : "ืืชืจืขืช ืคืืงืื ืืขืืจืฃ",
"data" : ["ืขืืืฃ ืขืื 218","ืขืืืฃ ืขืื 217"]
}
console.log(obj.data.join(', '))
var json = [];
var to = '[email protected],[email protected],[email protected]';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
json.push({"email":toSplit[i]});
}
Try this ES6 Version which has better perform code snippet.
'use strict';
let to = '[email protected],[email protected],[email protected]';
let emailList = to.split(',').map(values => {
return {
email: values.trim(),
}
});
console.log(emailList);