function main(message){
...
phone= JSON.parse(message.phoneNumbers);
... }
My input JSON is
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
The result I receive is omitting the "phoneNumbers" but I do want it.
Your data is correct, when i JSON.parse it, i get everything allright.
But you don't seem to access to your data in the right way. You must first parse the whole JSON, then you have a javascript object, and only then you can acces your property.
in detail:
var obj = JSON.parse(message);
var phone = obj.phoneNumbers;
or in short:
var phone = (JSON.parse(message)).phoneNumbers;
Related
I'm currently trying to code an application with javascript. It pulls data from a database and the response I'm getting is something like that:
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
But I need to have the JSON like that:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
How can I delete the parent values object in my JSON?
SHORT ANSWER:
Just access the values property like a JavaScript object.
LONG ANSWER:
You didn't post the JavaScript code snippet so it's quite difficult to give you an appropriate answer.
Assuming you have the following code:
const jsonString = getDataFromTheDB()
const jsonObject = JSON.parse(jsonObject) // still has the "values" layer
const values = jsonObject.values // what you want, without the "values" layer
// BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer
const valuesJSON = JSON.stringify(values, undefined, 2)
Based on this post :
just do this (consider json the variable that contains your json):
var key = "values";
var results = json[key];
delete json[key];
json = results;
console.log(json) will output the following:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
But you dont even have to do the last 2 steps of the code snippet above, you could also just directly use results variable and have the same output by console.log(results).
You could take the object and create a new variable with just the array.
var vals =
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
var arr = vals.values;
console.log(arr);
I'm trying to omit req.body data, when updating a resource in a collection, with only the fields that are null or '' for that existing resource in the collection.
But this could also be generic, that's why the title is more generic.
Anyways, imagine the following:
We have a user in our database with the following data:
{
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
The user is trying to update the existing resource with the following data:
{
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
Updated object should like like this:
{
"firstName": "John", // Unchanged because propety value already exists
"lastName": "Doe",
"address": {
"Address1": "Random street 1", // Unchanged because propety value already exists
"City": "NY", // Updated because existing value is empty ("")
"Country": "USA" // Updated because existing value is null
},
"email": "john.doe#mail.com" // Updated because existing value is empty ("")
}
I'm using mongoose, but I would rather implement this on the basic javascript object level
I am not aware of any library but below is the working example using recursion.
var oldObj = {
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
var newObj = {
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
updateObject(oldObj, newObj);
function updateObject(oldObj, newObj) {
Object.keys(oldObj).forEach( key => {
if (oldObj[key] && typeof oldObj[key] === 'object') {
updateObject(oldObj[key], newObj[key]);
} else {
oldObj[key] = oldObj[key] || newObj[key];
}
});
}
console.log("Modified Obj: ", oldObj);
Hope this may help you.
Sample JSON Data:
{
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]}
With this sample data I can display individual values from the results [] array with object.name and object.phone to look something like:
John Smith 555-555-1111<br />
Mary Jones 555-555-2222<br />
Edward Edwards 555-555-3333<br />
Abby Abberson 555-555-4444
What I am trying to do now is select just the people who's state value is NY and only display their object.name and object.phone:
John Smith 555-555-1111<br />
Edward Edwards 555-555-3333
I tried this lovely little block but all it did was print all the names, which makes sense after I tried it.
if (object.state = "NY") {
div.append(repName);
}
I can't seem to think of a way to only display those that share a the same state.
I'm probably searching for the wrong terms or have to go about this another way... please help!
You are using =(assignment operator),which is wrong.
You have to use ==(comparison operator)
So do like below:-
if (object.state == "NY") {
div.append(repName);
}
Working sample-
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
$(obj.results).each(function(k,object){
if (object.state == "NY") {
$('#final_data').append(object.name +" : "+object.phone+"<br/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="final_data"></div>
My one cent solution:
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
obj.results.forEach((value) => {
if (value.state === "NY") {
const li = document.createElement("li");
li.innerHTML = `${value.name} : ${value.phone}`;
document.querySelector("#final_data").appendChild(li);
}
});
<ul id="final_data"></ul>
Like Alive said you used the assignment operator = instead of comparison operator === or ==.
I have a document that resembles:
[
{
"subscriberid": "4355",
"Title": "Miss",
"FirstName": "FirstName",
"LastName": "LastName",
"EmailAddress": "thisisanemail#email.com",
"Mobile": "",
"Postcode": "B1 3qq",
"Gender": "",
"SubscribeDate": "2015-08-12 10:58:29",
"Birthday": "31-5-1985",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "1113111",
"attendreason": "Array",
"MarketingOptIn": "Y",
"Source": "WEBSITE",
"Login": [
{
"subscriberid": "4355",
"Created_at": "2017-05-18 10:09:44",
"IPaddress": "1.1.2.3"
}
]
},
{
"subscriberid": "125",
"Title": "",
"FirstName": "FirstName2",
"LastName": "LastName2",
"EmailAddress": "thisisalsoanemail#email.com",
"Mobile": "",
"Postcode": "tn39 4de",
"Gender": "",
"SubscribeDate": "2015-12-02 17:21:18",
"Birthday": "13-3-1922",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "8108200",
"attendreason": "Date",
"MarketingOptIn": "Y",
"Source": "FACEBOOK",
"Vouchers": [
{
"subscriberid": "213",
"Created_at": "2017-05-18 08:57:47",
"Source": "some website",
"offer": "50offMains",
"name": "50% off Mains"
}
],
"Login": [
{
"subscriberid": "123",
"Created_at": "2017-05-18 07:57:46",
"IPaddress": "1.2.3.4"
}
]
}
]
And I'm trying to turn it into a CSV, automatically. Normally this would be a very simple script with json2csv, but for some reason this time I'm having an issue that I'm struggling to troubleshoot. My file is being created, but with headers only and no data.
I read the docs on https://github.com/zemirco/json2csv and I'm thinking I would use dot notation for the fields but due to how it's setup, I'm unsure what would preceed the dot?
I tried CLI version and an actual JS Version but same deal. All I get is the headers. As you'll see in the script, I only care about parts of the JSON Document, but even if I try to do it all, I still only get the headers. My previous versions have all used glob, but the CLI and pointing directly to the file still nets the same result.
var json2csv = require('json2csv');
var fs = require('fs');
var glob = require('glob');
let fields =
[
"subscriberid",
"Title",
"FirstName",
"LastName",
"EmailAddress",
"Mobile",
"Postcode",
"Gender",
"SubscribeDate",
"Birthday",
"Kids",
"Kidsages",
"Student",
"Favourite",
"attendreason",
"MarketingOptIn",
"Source"
];
let dataInput = glob("path/**/toFile.txt");
var csv = json2csv({ data: dataInput, fields: fields });
fs.writeFile('output.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
I am currently working on a REST API / website project, where my REST API has to return an array of objects from the server, via a response and using GSON to make a Json array out of the data. However, when trying to get values from the javascript array for the website, I keep getting undefined. This is the array:
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [
{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}
],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [
{
"id": 1,
"number": "123124",
"info": "0x1"
}
]
}
];
When I try to call userArr[0].firstName, I get an error saying that it's undefined, even though the data is there. This is from a get call, which I am doing in my javascript from my REST API, which sends back this specific array. I have tried looping through the array, with multiple objects inside, however I am unable to retrieve any info at all.
Your userArr is an array of objects which do not have firstName property. They have only one property named 0x1 for some reason. And this 0x1 property has firstName property.
You can access firstName of 0x1 property using this notation:
userArr[0]["0x1"].firstName
Here is the working demo:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0]["0x1"].firstName);
By the way, there is a missing closing } bracket in the end of the array in your code.
I think if you write this code this way it is easy to understand and find the problem
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
"id": 1,
"address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
"infoList": ["0x1","0x2"]},
"phones": [{"id": 1,"number": "123124","info": "0x1"}]
}
}
];
You also missing the last second bracket.
Then you could use this console.log(userArr[0]["0x1"].firstName);
try this one
userArr[0]["0x1"].firstName
Incase value "0x1" is dynamic, you can access it by using Object.keys(userArr[0])[0] to get the first key of the object.
Here is solution:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);