JSON.stringify set root element - javascript

I want to convert my object into a JSON String where the root element should be the name of my object.
var data = {
name: 'qwertz',
age: 23,
skills: [
'html', 'css'
]
}
var json = JSON.stringify(data);
The output is:
{"name":"qwertz","age":23,"skills":["html","css"]}
But I want this:
{"data":{"name":"qwertz","age":23,"skills":["html","css"]}}
Can someone give me a hint how to reach this? Thanks you :)

As simple as that:
var json = JSON.stringify({ data: data });

Try this
JSON.stringify({'data':data})

Related

Unable to parse stringified array within an array

I have this example code:
let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]
let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);
Testing my code using this site: https://es6console.com/
It seems that I'm unable to parse & log the data at all.
Any ideas why this is happening?
Your option string is not following the JSON specs: in JSON every key and string value needs to be enclosed in double quotes. So this would work:
let testData= [{
name: 'Joshua',
age: 22,
option: '[{"value": "test"}]'
}, {
name: 'Ali',
age: 200,
option: '[{"value": "test2"}]'
}];
let parsedData = JSON.parse(testData[0].option);
console.log(parsedData);
I think the issue is that JSON object's fields should be wrapped in double-quotes.
E.g.
let testData = [{name:'Joshua',age:22,option:`[{"value":'test'}]`},{name:'Ali',age:200,option:`[{"value":'test2'}]`}]

Asynchronous Query JSON object

I have been playing around with a module from NPM called JSON-Query, I originally able to make the module function with JSON embedded in my js.
I have spent about two days attempting to make it query JSON that is external and in a JSON file.
The original code that was functioning looked something like this.
var jsonQuery = require('json-query')
var data = {
people: [
{name: 'Matt', country: 'NZ'},
{name: 'Pete', country: 'AU'},
{name: 'Mikey', country: 'NZ'}
]
}
jsonQuery('people[country=NZ].name', {
data: data
}) //=> {value: 'Matt', parents: [...], key: 0} ... etc
I was able to query the internal JSON to find the key I was looking for.
I realized I need the ability to update the JSON while the code is live, so I moved the JSON to its own file.
Currently my main JS file looks like this.
var jsonQuery = require('json-query');
var fs = require('fs');
function querydb(netdomain){
fs.readFile('./querykeys.json', 'utf8', function (err, data) {
if (err){console.log('error');}
var obj = JSON.parse(data);
console.log(jsonQuery('servers[netshare=Dacie2015].netdomain', {
obj: obj
}));
});
}
querydb();
My JSON file that contains the json looks like this.
{
"servers": [
{"netdomain": "google.com", "netshare": "password", "authip":"216.58.203.46"},
{"netdomain": "localhost", "netshare": "localghost", "authip":"127.0.0.1"},
{"netdomain": "facebook.com", "netshare": "timeline", "authip":"31.13.69.228"}
]
}
The issue I have ran into, I am unable to query the JSON anymore, when the function QueryDB() is ran, no matter what is in the place to query the JSON, i get no response locating my key.
Currently the response I get from the server when i try to query the JSON file is
{ value: null,
key: 'netdomain',
references: [],
parents: [ { key: 'servers', value: null }, { key: null, value: null } ] }
To be abundantly clear, i believe my issue is the way i call my object into play, i have played with the structure of the JSON-Query and have been unable to accomplish being able to isolate a key.
Any help on this would be amazing, the module that i am working with can be found on npm at [NPM]https://www.npmjs.com/package/json-query
Thank you
I think this is just a typo. Shouldn't this:
obj: obj
be this?
data: obj

How to append to json object in JavaScript

How can I append to a json object.
I define the JSON as follows:
$scope.usergroupJson = {'groupId':1,'name':'CEO'}
I would like to append {'groupId':2,'name':'Director'} to the usergroup. I have tried:
$scope.usergroupJson.push({'groupId':2,'name':'Director'});
But I get an undefined error. I know this is trivial but any help would be appreciated. Thanks in advance
We can use like this
var json = {};
json["employees"] = [];
var usergroupJson = json["employees"];
usergroupJson.push({
'groupId': 1,
'name': 'President'
});
usergroupJson.push({
'groupId': 2,
'name': 'Vice-President'
});
usergroupJson.push({
'groupId': 3,
'name': 'Product Manager'
});
you must usergroupJson to be array
$scope.usergroupJson = [{'groupId':1,'name':'CEO'}]

Angular Ajax request sending object

i am editing content in an object saved in my AngularJs scope. Once submited i execute the following function:
$scope.saveQuestion = function(){
var request = $http({
method: "post",
url: "/manager/evaluations/evaluations/manage_questions/537c6179-8ed8-49b4-ac6b-25715f550349",
data: {EvaluationQuestion: $scope.newquestion}
});
}
$scope.newquestion has the following object:
[relevance: 3, evaluation_topic_id: 1, type: "text", action: "add", name: "asdfasdfsadfas"]
But the ajax request on the is just showing a Request Payload with:
Request Payloadview source
{EvaluationQuestion:[]}
EvaluationQuestion: []
Can any one guess why the sent data is empty?
It seems your $scope.newquestion is an Array, not an Object.
JSON doesn't support an Array data type with named keys in it. For example:
var foo = [];
foo['bar'] = 'One';
foo.baz = 'Two';
JSON.stringify(foo); // return "[]"
If the $scope.newquestion isn't required to be an Array, just use an Object.
Instead of
$scope.newquestion = [];
change it to:
$scope.newquestion = {};
I think you are using a wrong JSON syntax in $scope.newquestion.
Here you are defining an object which is supposed to be enclosed in {} but you are enclosing it in [] which stands for an array. I js arrays you cannot have [name1: value1, name2: value2].
Try replacing the square brackets with curely brackets, something like this:
{relevance: 3, evaluation_topic_id: 1, type: "text", action: "add", name: "asdfasdfsadfas"}
Hope that helps.
Try this:
data: {EvaluationQuestion: angular.toJson($scope.newquestion)}

Adding to a JSON string

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Categories

Resources