String array to jSON array in Javascript? - json

I have a string file like this
["ORM.mp4","bla.bla","blaa.blaa"]
an any body tell me how can I convert it to array of jSON object.
I have tried various methods like json.stringify() then json.parse()etc.
None of them worked.
Any help would be highly appreciated!

Use eval https://www.w3schools.com/jsref/jsref_eval.asp
a = eval('["ORM.mp4","bla.bla","blaa.blaa"]')
console.log(a)

var test = '["ORM.mp4","bla.bla","blaa.blaa"]';
var data = JSON.parse(test);
console.log(data );
You can use JSON.parse() for parsing json.

var obj = ["ORM.mp4","bla.bla","blaa.blaa"].reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});

Related

How to remove list square brackets from serialized json string

I'm calling a stored procedure using a controller.
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
jsonResult = JsonConvert.SerializeObject(insert_query); // <-- using Newtonsoft.Json
The json string is the following:
"[{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}]"
Is there a way to remove the [ and ] brackets?
I want the json string to be:
{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
if(insert_query!=null && insert_query.Count()>0)
{
jsonResult = JsonConvert.SerializeObject(insert_query[0]);
}
This will serialise only 1st element so it wont have []

Deserialize Json Object list with id as root with jackson

I have this json structure from firebase where it's a list of objects but the root of each object is the ID
How can I serialize this to a list of object with the id/root as a member variable. This is for Spring boot so I would prefer if it were a Jackson2 solution.
This may be the same question as Jackson JSON key as value in Java but my answer is better because it doesn't require an extra/useless class
val reader = ObjectMapper().reader()
val tree = reader.readTree(testJson)
val eventList = mutableListOf<Event>()
tree.fields().iterator().forEach {
val event = Event(
it.key,
it.value.get("name").asText(),
it.value.get("description").asText(),
it.value.get("startDate").asText(),
it.value.get("startTime").asText(),
it.value.get("endDate").asText(),
it.value.get("endTime").asText(),
it.value.get("imageUrl").asText()
)
eventList.add(event)
}
I have found a solution using jackson in kotlin, it's not the prettiest but it works. the fields method returns a map of children. So, I am iterating through the map and adding the key as the object id member and then grabbing the rest of the data from the nested map.
Sorry, I am not a pro in Jackson. But there is a simple way to transform your object in JavaScript -- and perhaps this will lay the foundation for something that can be ported to Jackson (java?)
This is the convertData function that does the transform:
var convertData = function (d) {
var arr = [];
for(var prop in data)
{
var el = { "id": prop };
var otherprops = data[prop];
for(var otherprop in otherprops)
{
el[otherprop] = otherprops[otherprop];
}
arr.push(el);
}
return arr;
}
Tnis is what my sample data looks like after the conversion (slightly different values than yours):
[{"id":"-L8eoUd5mqJGnXDVSmb0","description":"With a great description","endDate":"12/31/2018","endTime":"03:00","imageUrl":"/favicon.ico","name":"Here's a Good Event","startDate":"12/01/2018","startTime":"12:00"},{"id":"-L8jO6Zhz976hvoLUiga","description":"Another item","endDate":"12/30/2018","endTime":"03:05","imageUrl":"/favicon2.ico","name":"Event #2","startDate":"12/11/2018","startTime":"12:03"}]
Link to JSFiddle: https://jsfiddle.net/2t1s2are/13/
Hope this helps!!

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing
As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})
You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.

how insert " in numbers of my json [NODEJS]

i have a JSON like this:
{"name1":123,"name2":123,"name3":123}
i want put "" in numbers To stay like this:
{"name1":"123","name2":"123","name3":"123"}
Anybody know a nodejs code to do this?
Assuming the object is already parsed and stored in a variable somewhere, you can do:
Object.keys(myObject).reduce((o, k) => Object.assign(o, {
[k]: myObject[k].toString()
}), {})
As Judson Terrel was saying above, you should consider using JSON.stringify(myJsonObject)
but if you so desired to use regex, here it is
let str = '{"name1":123,"name2":123,"name3":123}';
let result = str.replace(/\b(\d+)/g, "\"$1\"");
console.log (result);
//console-output => {"name1":"123","name2":"123","name3":"123"}
The simplest way is to parse the JSON string to an object using JSON.parse, and then convert the object values to string with the String function, like this:
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)

Nodejs jsonArray parsing

I have a json object i want to get data from it!
here is my json object
"[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]"
and here is my code :
var json = JSON.parse(data);
var androidVersionName = data.rowsets['androidVersionName'].row;
console.log(androidVersionName);
and i get this error :
Cannot read property 'androidVersionName' of undefined
how can i parse data from this jsonObject?
A valid JSON based on your object:
{
"androidVersionName":"2.3.3",
"androidVersionId":10,
"androidId":"fa0bef4b5a48eacb",
"mobileModel":"sdk",
"mobileManufacturer":"unknown",
"mobileId":"GRI34",
"mobileProduct":"sdk",
"applicationName":"com.example.socketclient",
"applicationVersionName":1.0,
"applicationVersionCode":1,
"applicationState":"INACTIVE",
"screenWidth":480,
"screenHeight":480,
"screenDensity":240,
"screenDensityName":"hdpi",
"atdPackages":"com.atd.panberes(1)"
}
You can't parse it to object. But you can transform it to JS object.
var data = "[androidVersionName=2.3.3, androidVersionId=10, androidId=fa0bef4b5a48eacb, mobileModel=sdk, mobileManufacturer=unknown, mobileId=GRI34, mobileProduct=sdk, applicationName=com.example.socketclient, applicationVersionName=1.0, applicationVersionCode=1, applicationState=INACTIVE, screenWidth=480, screenHeight=480, screenDensity=240, screenDensityName=hdpi, atdPackages=com.atd.panberes(1)]";
var result = {};
data.replace(/(\w+)=(\w+)/g, function(_, left, right) { result[left] = right; })
console.log(result);