If I parse a JSON object in Node.js like this
var datap = JSON.parse(data);
I get an hierarchical object (as visible in the debugger):
datap = object
account1 = object
name = "A"
type = "1"
account2 = object
name = "B"
type = "2"
Now I would like to add an account3 with a line like this
datap.append("account3")
and ofcourse after this
datap.account3.append({"name":"C", "type":"1"})
My Javascript knowledge is still limited, is there a possibility to do so?
Once the json is parsed you can just use in as an Object:
var datap = JSON.parse(data);
datap.account3 = { name :"C", type :"1"};
Related
How can I access a specific data from following JSON without getting undefined?
var myObj = '{"isTrue":"true","id":"1"}';
var theKey = 'isTrue';
alert(myObj[theKey]); //I get undefined here
You need to parse that JSON as String before to access any property from it.
JSON.parse(myObj)
var myObj = '{"isTrue":"true","id":"1"}';
var theKey = 'isTrue';
alert(JSON.parse(myObj)[theKey]);
I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);
I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
works. But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
I tried some things but its not working :(
I need to create the JSON like this because I needs variables as parents
I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
That's not a JSON array, that's a JavaScript object.
But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
That's because you're setting a property on a string primative. That will temporarily promote the string primative to an object, set the property, and then throw away the object, effectively doing nothing.
To make someJSON.number an object, create an object just like you did for someJSON and add properties to it. Or you can do it all at once:
let obj = {
number1: {
date: "19.01.2017"
}
};
If you want "someString" in there somewhere, just put it on another property:
let obj = {
number1: {
str: "someString",
date: "19.01.2017"
}
};
You have to create the "number1" object first. Note that you won't be able to set a string value for "number1" as it is now an object.
let someJSON = {};
someJSON["number1"] = {};
someJSON["number1"]["date"] = "19.01.2017";
I'm trying to push an object inside an array with dynamic attribute name.
Let's say we have the following variables defined
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue";
parsedJSON = JSON.parse(myJSON);
parsedJSON["students"].push({attribName : myValue});
myJSON = JSON.stringfy(parsedJSON);
The example isn't working. Is there a way to push an object with dynamic attribute name?
From MDN,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
Also note that input you has provided is object, not json
var myJSON = {
"students": [{
"name": "Your Name"
}, {
"name": "My Name"
}]
};
var attribName = "name";
var myValue = "myValue";
var obj = {};
obj[attribName] = myValue;
myJSON["students"].push(obj);
console.log(myJSON);
function(key, value, json) {
var obj = {};
obj[key] = value;
json['students'].push(obj);
return arr;
}
You can also do the modification in your code :
myJSON = {"students" : [ {"name":"Your Name"}, {"name":"My Name"} ] };
attribName = "name";
myValue = "myValue123";
myJSON["students"].push({attribName: myValue});
console.log(myJSON);
I'm trying to initialize an object in typescript which requires a JSON string for the "options" parameter. To be precise it is the object here. The options parameter is required to be a JSON string and not an object for initializing the dijit.
Is there a way to create a JSON string from a typescript object without it being a manual process?
Please DO NOT link any questions which don't specifically say "TypeScript" as this question specifically relates to TypeScript. While a derivative of JavaScript the way that you write code is different and therefore this is the only post asking this question currently relating to TypeScript.
Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.
TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:
JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
JSON.stringify() method converts a JavaScript object or value to a JSON string.
Example:
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';
const JSobj = JSON.parse(jsonString);
console.log(JSobj);
console.log(typeof JSobj);
const JSON_string = JSON.stringify(JSobj);
console.log(JSON_string);
console.log(typeof JSON_string);
You can use the standard JSON object, available in Javascript:
var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);
Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.
const temp = [];
const t = {
name: "name",
etc: [{
a: 0
}],
};
for (let i = 0; i < 3; i++) {
const bla = Object.assign({}, t);
bla.name = bla.name + i;
bla.etc[0].a = i;
temp.push(bla);
}
console.log(JSON.stringify(temp));
If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:
const fsExtra = require('fs-extra');
fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})