How to add element to JSON object with Javascript - javascript

So say I have a JSON object like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
And I can't modify it when it is created. But I want to make it look like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}
So how would I do that with javascript?

In the context of JavaScript, there's no such thing as a "JSON Object". What you've got there are JavaScript objects. JSON is a data interchange format that was of course derived from JavaScript syntax, but in JavaScript directly an object is an object. To add a property, just do so:
var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;
Now, if what you've really got is a string containing a JSON-serialized object, then the thing to do is deserialize, add the property, and then serialize it again.

With the way your question is currently structured:
> myJson = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI"}
> myJson.checked = true;
true
> myJson
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI", checked: true}
But I bet you may have to decode and recode first with:
JSON.parse(myJson)
JSON.stringify(myJson)
The entire thing may look like
// get json and decode
myJson = JSON.parse(response);
// add data
myJson.checked = true;
// send new json back
$.post('/someurl/', JSON.stringify(myJson));

Related

How to access an attribute from a JSON line saved in a position from an array?

This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined

How to add an object to JSON (nodeJS)

Yes I already know about
json.newvalue = 'newvalue'
But I'm not looking for that...
I have an empty JSON
plugins = {};
Now I need to add 5 items to it for example:
{"name":"test"}
{"name":"test2"}
I am looking for something like this: plugins.add({"name":"test"})
First, json is a string representation of an object, what you have in your code is an object. However, it seems that you don't want a JavaScript object, but an array.
var plugins = [];
plugins.push({"name":"test"});
plugins.push({"name":"test2"});
plugins will now be
[
{"name", "test"},
{"name", "test2"}
]

C# Dictionary equivalent in JavaScript

Is there exist any kind of c# dictionary in JavaScript. I've got an app in angularjs that requests data from an MVC Web Api and once it gets, it makes some changes to it. So the data is an array of objects, which is stored in the MVC Web Api as a Dictionary of objects, but I convert it to list before passing it throug network.
If I convert the Dictionary directly to JSon I get something like:
array = [ {Id:"1", {Id:"1", Name:"Kevin Shields"}},
{Id:"2", {Id:"2", Name:"Natasha Romanoff"}}
];
Well the objects are a little more complex, but you've got now an idea. The problem is that this format is even harder to operate with (I've got alphabetical keys or ids). So is there any equivalent to a dictionary? It's quite simple to do thing like:
Object o = dictionary["1"];
So that's it, thank in advance.
You have two options really, although both essentially do the same thing, it may be worth reading a bit more here, which talks about associative arrays (dictionaries), if you wish to tailor the solution:
var dictionary = new Array();
dictionary['key'] = 'value'
Alternatively:
var dict = [];
dict.push({
key: 'key',
value: 'value'
});
Update
Since ES2015 you can use Map():
const dict = new Map();
dict.set('{propertyName}', {propertyValue});
I know this question is a bit older, but in ES2015 there is a new data structure called map that is much more similar to a dictionary that you would use in C#. So now you don't have to fake one as an object, or as an array.
The MDN covers it pretty well. ES2015 Map
Yes, it's called an object. Object have keys and values just like C# dictonaries. Keys are always strings.
In your case the object would look like this:
{
"1": {
"Id": 1,
"Name":" Kevin Shields"
},
"2": {
"Id": 2,
"Name": "Natasha Romanoff"
}
}
The default ASP.net serializer produces ugly JSON. A better alternative would be Json.NET.
My Example:
var dict = new Array();
// add a key named id with value 111
dict.id = 111;
//change value of id
dict.id = "blablabla";
//another way
// add a key named name with value "myName"
dict["name"] = "myName";
//and delete
delete dict.id;
delete dict["name"]
//another way
dict = {
id: 111,
"name": "myName"
};
//And also another way create associate array
var myMap = { key: [ value1, value2 ] };

Retrieving value from nested Javascript Object

I'm scratching my head here why I can't figure this out. It should be easy. I am trying to work with a Javascript object which looks like so:
Object {object: "clip", function: "list", data: Object, items: 1} (console log )
This Object is stored in a variable called data.
if I do var items = data.items I get the number I expect (1). What I cannot seem to get is what is in the data section.
The data.data logged to the console looks like this:
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"…}
I would expect if I wanted the Clipid I would be able to do:
var Clipid = data.data['Clipid'] or data.data.Clipid; however this always comes up null.
I've tried a number of things, but nothing works. I'm sure it's something silly or small I'm missing but any insight is appreciated. Thanks!
If it helps the data comes from jQuery.parseJSON( jsonString )
Note ** If I do this:
var objd = data['data'];
var arv = $.map(objd, function (value, key) { return value; });
I am able to get values like arv[0] etc but I'd prefer to go by key if possible...
Note 2 - It's the JSON Formatting I'm decoding
Hey sorry about this, I noticed the encoding is borked. It looks like if I do:
console.log( data.data["\u0000Clip\u0000id"] ); it wotks! It must have to do with the json_encode.
There's a small typo I guess-
data.data.Clipid
note the small i
It looks like the data is an object, not a dictionary, so you would do var Clipid = data.data.Clipid; to get at the information inside.
You can't do data.data['Clipid'] because you named the attributes using string literals, and the proper syntax you used (data.data.ClipId) has a typo, as mentioned.
if your "Object" in the "data" variable, you just have to do
var clipid = data.Clipid;
var object = {object: "clip", function: "list", data: {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}, items: 1}
console.log(object);
Object {object: "clip", function: "list", data: Object, items: 1}
console.log(object.data)
Object {Clipid: "1", ClipprojectID: "2", Clipnote: "This is a sample clip", Clippath: "http://www.jplayer.org/video/m4v/Big_Buck_Bunny_Trailer_480x270_h264aac.m4v", Clipduration: "33"}
console.log(object.data.Clipid)
1
This works fine for me, we would need to see your code to see why you are specifically having problems.
It had to do with the JSON encode method in PHP... All the answers stated was what I had tried and are correct, it was just a valid JSON string which had had unexpected unicode characters.
To fix it I needed to do this: $json = str_replace('\u0000', "", json_encode( $response )); Where response was my array of data to be cnverted

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

Categories

Resources