set array as value in json format in Javascript - javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.

Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");

You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}

In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Related

Naming a JSON array using Jquery

I have an array of JSON:
[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
I want it to be:
{
gitdList: [
{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},
{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}
]
}
I searched and am finding solutions regarding php only , to use json.encode.
How do I do it using JQUERY?
Have you try like this way? just create an empty object like this object = {} and assign your existing value i.e avatar_urls to it with your desired key i.e gitdList. Hope this will work for you.
var avatar_urls = [{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
var object = {};
object.gitdList = avatar_urls;
console.log(object);
Edit: pretty neat and better way to do it.
var object = { gitdList: avatar_urls};
console.log(object);
maybe like this:
var data=[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}];
var new_data={ 'gitdList': data };
console.log(new_data);

How Split and Find Text Value in Array

How can I spilt below Array and print verificationCode= "value" in consle.log
var backup = [{kind=admin#directory#verificationCode, etag="HIWxtAjmBmqPQjjDV2Duo181uSc/ojhx3q8-0EqFY6M1x0NOJ85j1xg", userId=116800256069112846055, verificationCode=37140335}]
You need to correct your JS object to be in this format here.
var backup = [
{kind:"admin#directory#verificationCode",
etag:"HIWxtAjmBmqPQjjDV2Duo181uSc/ojhx3q8-0EqFY6M1x0NOJ85j1xg",
userId:"116800256069112846055",
verificationCode:"37140335"}
]
and then you can use the following to access your values
backup[0].verificationCode;

Turn Observable Array into nested JSON

I'm having a problem getting an array of information stored properly as JSON.
I made a fiddle to illustrate the problem. Enter a set of tags and take a look at the console to see the output.
More explanation:
So I have an input that takes in a comma-separated list of tags, which I then format.
function createTagArray() {
// given an input value of 'tag1, tag2, tag3'
// returns array = ['tag1', 'tag2', 'tag3']
}
I thought what I needed to do next was the following:
loop over the array and create a 'tag' object for each item which also includes an id for the tag and the id of the contact the tag is associated with.
Each object is pushed to tags, an observable array.
function single_tag(id, contactId, tagLabel) {
var self = this;
self.id = id;
self.contactId = contactId;
self.tagLabel = tagLabel;
}
function createTags() {
var array = createTagArray();
for (var i = 0; i < array.length; i++) {
self.tags().push(new single_tag(uuid.generate(), self.contactId, array[i]));
}
}
Then, I converted it into JSON
self.contactInformation = function() {
return ko.toJS({
"id": self.contactId,
"firstname": self.firstname(),
"lastname": self.lastname(),
... other fields ...
"tags": self.tags(),
})
}
But, when I inspect the console output of calling this function, tags is a collection of arrays, not a nice json object.
How do I get it formatted correctly?
I tried this suggestion, and the tag json is structured correctly, but it is stored with escaped quotes, so that seems wrong.
Thanks for all the help!
I would recommend you knockout.mapping plugin for KO, it allow map complicated JSON structure to view model, even without declarations.
From the documentation
Let’s say you have a JavaScript object that looks like this:
var data = {
name: 'Scot',
children: [
{ id : 1, name : 'Alicw' }
]
}
You can map this to a view model without any problems:
var viewModel = ko.mapping.fromJS(data);
Now, let’s say the data is updated to be without any typos:
var data = {
name: 'Scott',
children: [
{ id : 1, name : 'Alice' }
]
}
Two things have happened here: name was changed from Scot to Scott and children[0].name was changed from Alicw to the typo-free Alice. You can update viewModel based on this new data:
ko.mapping.fromJS(data, viewModel);
And name would have changed as expected. However, in the children array, the child (Alicw) would have been completely removed and a new one (Alice) added. This is not completely what you would have expected. Instead, you would have expected that only the name property of the child was updated from Alicw to Alice, not that the entire child was replaced!
...
To solve this, you can specify which key the mapping plugin should use to determine if an object is new or old. You would set it up like this:
var mapping = {
'children': {
key: function(data) {
return ko.utils.unwrapObservable(data.id);
}
}
}
var viewModel = ko.mapping.fromJS(data, mapping);
In the jsfiddle you were using Knockout 3.0 which doesn't have support for textInput. This was added in 3.2. To use version 3.2 you need to use a cdn such as this: http://cdnjs.com/libraries/knockout
There was typeo in your binding. sumbit should be submit.
There was a problem with your constructor for single_tag. id was not used so I removed it:
function single_tag(contactId, tagLabel) {
var self = this;
self.contactId = contactId;
self.tagLabel = tagLabel;
}
Currently also contactId is not set because the observable has not been set to a value.
To convert to JSON you need to use ko.toJSON instead of ko.toJS:
self.contactInformation = function() {
return ko.toJSON({
"firstname": self.firstname(),
"tags": self.tags(),
})
}
Now when the console writes out an array appears:
{
"firstname":"test",
"tags":[
{"tagLabel":"test1"},
{"tagLabel":"test2"},
{"tagLabel":"test3"}
]
}
JsFiddle
So my problem was more basic than I was realizing. I'm using JSON Server to serve up my data, and I was pulling information from two parts of the database (contacts & tags).
When I tried to update my tags, I was trying to apply them to a property that didn't exist on the contact JSON in my database. Posting the tags separately worked though.

Addressing a String variable inside a Json with javascript

I'm new with Javascript and bumped into a funny problem.
I have a Json which is alike the following:
{
"TEAM-8f382740": {[
{info1},
{info2},
{info3}
]}
}
I'm trying to get the content behind that "TEAM-8f382740" in my code:
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data.??; //what to put here to get just {info1},{info2}...
});
Problem is the 'TEAM-8f382740' is a variable and the same time in a tricky form.
I tried the following:
$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data.$scope.teamName; //data.teamName doesn't work either
});
So how to get that [{info1},{info2},{info3}] content from the Json?
I tried with other kind of Jsons and seems if instead of "TEAM-8f580740" there is for example the word "champions" that is not changing, then I can just get the content behind it by
$scope.champions = data.champions;
You were close:
$scope.teamName = 'TEAM-8f580740'; //or var teamName='TEAM-8f580740';
$http.get('https://eune.api.pvp.net/api/lol/eune/v2.4/team/TEAM-8f580740')
.success(function(data) {
$scope.champs = data[$scope.teamName];
});
If you want to get a value from a Javascript object, there are two options: using dot notation or bracket notation. Say you have this object:
var foo = {
"key": {"another_key": "baz"}
}
You can get the value using the dot notation:
foo.key
#returns {"another_key": "baz"}
If you don't know they name of the key until runtime, you can't use the dot, so you can use bracket notation to accomplish the same thing.
var key = "key"
foo[key]

Add objects to JSON

I have a JSON that looks like this:
{
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
}
When I add an object to it:
addObj[obj.length] = saveobject;
the previous content gehts replaced.
When I make an array out of it and push the object:
addObj = [loadedJSON];
addObj.push(saveObj);
I get this after the first
[Object]
after the second so fare so good
[Object, Object]
and after the third it gets messed up
[Array(2), Object]
What do I miss?
I hope some one can help with this?
The way I hoped it would look like is this.
[Object, Object, Object, ...and so on]
EDIT
to be More specific
when I add a new Object I load the JSON file in a variable and then I try to add the new Object.
Which works for the first two objects but the third one is added to the first object so that I got this result.
[Array(2), Object]
I dont want it nested like this! But how do I get it like this?
[Object, Object, Object].
EDIT
So eventually you all were right I just mixed up the array when i loaded it the second time every thing is fine now thank for pointing me in the right direction.
on the first time:
var a= [];
var b= {};
b= 'some things';
a.push(b);
and wenn a.length != null
b= 'the rest';
a.push(b);
and now everything is just as expected!
As far as I understand it, this has nothing to do with JSON.
It seems you want to have an array storing successive instances of a given object (that happens to have been encoded in JSON at some point, but for the problem at hand we could not care less).
First, create a sorage array.
Then push each new instance into it.
var storage = []; // your storage array, initially empty
// ....
while (some_guy_wants_to_send_me_something ())
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
EDIT:
If you use a button:
var storage = []; // your storage array, initially empty
// ....
function add_whatever_object ()
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
// HTML
<button type="button" onclick='add_whatever_object();'>
I still don't see where the catch is.
check the if it is an array:
Array.isArray(loadedJSON) //true
do this:
loadedJSON.push(saveObj);
if it was not an array push it to an array:
var myarray = [];
myarray.push(loadedJSON);
an then push your other object:
myarray.push(saveObj);
an so on:
myarray.push(otherObj);
I am a little unclear on what you actually want, but based on a little speculation I was able to write the following code for you. I hope this will solve your problem.
var a ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var b ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var c ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var ObjArr = [];
ObjArr.push(a);
ObjArr.push(b);
ObjArr.push(c);
console.log(ObjArr);
Here is the fiddle to it => http://jsfiddle.net/rB3Un/

Categories

Resources