I have json object like this:
var client = {
"id": 1,
"name": "John Doe",
"name2": "Jane Doe",
"email": "John#test.com",
"phone": "+1-306-5555555",
"phoneType": "Home",
"phone2": "+1-306-5556666",
"phone2Type": "Business",
"gender": "Male",
"address": "1000 Center AVE",
"postCode": "S7J 1P3",
"city": "Saskatoon",
"province": "SK",
"country": "CA",
"dob": "1990-12-11T02:00:00.000Z",
"maritalStatus": "Single",
"occupation": "Software Developer",
"createdAt": "2015-12-07T08:14:21.000Z",
"updatedAt": "2016-01-19T13:35:10.000Z"
};
Which I want to convert into XML, this isn't a problem I know there great library like x2js that can do that for me.
My problem is xml file, need to follow a standard like this:
<GeneralPartyInfo>
<NameInfo>
<PersonName>
<Surname>Doe </Surname>
<GivenName>John</GivenName>
</PersonName>
<SupplementaryNameInfo>
<SupplementaryName>Jane Doe</SupplementaryName>
</SupplementaryNameInfo>
</NameInfo>
<Addr>
<DetailAddr>
<StreetName>Centre</StreetName>
<StreetNumber>1000</StreetNumber>
<csio:StreetTypeCd>AVE</csio:StreetTypeCd>
</DetailAddr>
<City>Saskatoon</City>
<StateProvCd>SK</StateProvCd>
<PostalCode>S7J 1P3</PostalCode>
<CountryCd>CA</CountryCd>
</Addr>
<Communications>
<PhoneInfo>
<PhoneTypeCd>Phone</PhoneTypeCd>
<CommunicationUseCd>Home</CommunicationUseCd>
<PhoneNumber>+1-306-5555555</PhoneNumber>
</PhoneInfo>
<PhoneInfo>
<PhoneTypeCd>Phone</PhoneTypeCd>
<CommunicationUseCd>Business</CommunicationUseCd>
<PhoneNumber>+1-306-5556666</PhoneNumber>
</PhoneInfo>
</Communications>
you can xml is nested while my json isn't, not mention name need to spliced to firstName and lastName and be inside PersonName which is child of NameInfo, and GeneralPartyInfo be the root parent (same thing for the address).
there two problems I have, the first one is a missing tags for example firstname is inside PersonName which inside NameInfo which inside GeneralPartyInfo and I can't do this
var firstName = client.name.split(' ').slice(0, -1).join(' ');
var lastName = client.name.split(' ').slice(-1).join(' ');
delete client.name;
client.PersonName.push({
GiveName: firstName,
Surname: lastName,
});
because JSON is an object not an array, it requires for me to convert JSON into an array (which is not recommended by other professionals here in SO), or I can save each one (Name, address, communication) into it separate json object then concat all of them together abdthe only way I found in SO to add parent json object was like this
var obj = {fistName: client.name.split(' ').slice(0, -1).join(' '), lastName: client.name.split(' ').slice(-1).join(' ');};
var obj2 = { "PersonName" : obj };
var obj3 = { "NameInfo" : obj2 };
my second problem is find a way to replace keys for example I want to replace postcode to PostalCode or phoneType to CommunicationUseCd
or just do it this way
var xml = "<GeneralPartyInfo><NameInfo><PersonName>
<Surname>" + client.name.split(' ').slice(0, -1).join(' '); + "</Surname>
<GivenName>"+client.name.split(' ').slice(-1).join(' ')+"</GivenName>"
but this solution is tedious, not efficient and doesn't look pretty and I'm looking more for stability and cleanliness of code.
For example How can I manipulate a json object to add parent to selected elements then I can replace keys through list that have keys to be replaced for example.
var translationObj = {
"firstName": "GivenName",
"lastName": "PersonName",
}
PS: I have lodash/underscore installed so a solution using underscore would be great.
Related
Let's say I have this JSON in this variable person:
{
"firstName": "First Name"
"lastName": "Last Name"
"address": {
"city": "New-York",
"street": "Some Street"
}
}
Now, if I want the value of street, all I have to do is person[address][street]
I was wondering if there is a simple way to do so, let's say I have all the fields concatenated like:
const index = 'address:street'
I'm looking for a simple way to achieve the value like person[index]
Is there a way to do so? thanks!
If you have a string variable that has all the required fields to access the value in the right order like below (fields separated by a dot):
const index = "address.street";
Then you can get the requested value by using the eval function in javascript:
eval("person."+index);
This returns the required result: "Some street".
Not sure if this is what you're after but this would work:
const cstring = "value1:value2:value3";
const [one, two, three] = cstring.split(':');
console.log(one) // 'value1'
So that uses array destructuring.
Found the answer, I installed lodash and then:
import _ from 'lodash';
const person = {
"firstName": "First Name"
"lastName": "Last Name"
"address": {
"city": "New-York",
"street": "Some Street"
}
}
const index = 'address.street'; // changed it to be split by . instead of :
_.get(person, index);
I'm trying to create a function that when called will update a specific object in json file. However, it updates the object as well as creating a new one.
I've tried many different methods in trying to get this to work, but all have failed. The closest I've got to it working is the code shown below, but it still doesn't do what is required.
This is my function:
var fs = require('fs');
var _ = require("underscore");
module.exports = {
personalUpdate: function (id, forename, surname, dob, gender, callback) {
let rawdata = fs.readFileSync('data.json');
let data = JSON.parse(rawdata);
let filtered = _.where(data['students'], { id: id });
let all = filtered[0];
all.forename = forename;
all.surname = surname;
all.dob = dob;
all.gender = gender;
data["students"].push(all);
fs.writeFileSync('data.json', JSON.stringify(data, null, 2), (err) => {
if (err) throw err;
});
callback("success");
}
}
And this is the JSON file that I want to update:
{
"teachers": [
{
"name": "",
"email": "",
"password": "",
"formGroup": "",
"id": ""
}
],
"students": [
{
"surname": "test",
"forename": "test",
"dob": "",
"homeAddress": "",
"homePhone": "",
"gender": "",
"tutorGroup": "",
"schoolEmail": "",
"grades": [
{
"french": 8,
"maths": 7
}
],
"id": ""
},
{
"surname": "test2",
"forename": "test2",
"dob": "",
"homeAddress": "test2",
"homePhone": "",
"gender": "",
"tutorGroup": "",
"schoolEmail": "",
"grades": [
{
"french": 9,
"maths": 8
}
],
"id": ""
}
]
}
I had to remove and change the objects and info inside them, as it contained confidential information.
When running this function, it finds the object that is specified in the parameter. It then updates that object, but it then creates another object at the bottom of the original JSON object, which it is not supposed to.
Also, is there a better way to update the specific objects in the JSON file?
tl;dr
The result set is duplicating because you are pushing it into the array
The change is being applied due to the variables holding the same object reference, so they are being mirrored across objects that share the same pointer.
Explanation
It creates a new one due to the data["students"].push(all); instruction.
When you manipulate objects in javascript you need to be aware of how the reference between them work, so you can avoid bugs and use them in your benefit.
For example, take this set of instructions:
let a = {"x": 1};
let b = a;
b.x = 3;
console.log(a) // it will output {"x": 3}
Notice that we:
Create an object with the prop x equal 1 and assign it to the variable a
Initialize a variable b with the value of a
Change the property x on the variable/object b
Then we can observe that the change was also reflected in the variable a, due to the object reference.
So, basically this is exactly what is happening with your instructions when you do all.forename = forename; it changes the variable all, but also the original object which it derives from.
Here is a nice reference that explains this concept more in-depth
#EDIT
I strongly advise you not using the sync version of functions like readFileSync since this blocks the event loop. Here is the official guidelines about it
I currently have an object:
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
}
and I want to append it to "users.json":
[
{
"username": "Andy",
"surname": "Thompson",
"id": [0],
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
]
Do you know how I might be able to do this?
Thanks in advance.
This answer is assuming that you are working under Node.js.
As I understand your problem you need to solve a few different programming questions.
read and write a .json file
const fs = require("fs");
let usersjson = fs.readFileSync("users.json","utf-8");
transform a json string into a javascript array
let users = JSON.parse(usersjson);
append an object to an array
users.push(obj);
transform back the array into a json string
usersjson = JSON.stringify(users);
save the json file
fs.writeFileSync("users.json",usersjson,"utf-8");
If your code is running in the browser and users.json is an output file, I guess you already have access to its content.
Use the push() method.
Also, note the missing commas in your objects.
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
};
var users = [
{
"username": "Andy",
"surname": "Thompson",
"id": [0]
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
];
users.push(obj);
console.log( JSON.stringify(users) );
Now that you have the updated array of objects you can upload it to the server (check this question) or offer a download to the user (check this other question).
As you have been already told, there is no way to directly update client-side a file in the server. It is also not possible to save it directly into the client filesystem.
I am wondering how would I get the next JSON item if I have the key in JavaScript. For example, if I provide the key 'Josh' how would I get the contents of 'Annie' along with the key 'Annie'? Would I have to process the JSON in an array and extract from there?
In addition, I believe that there is a proper term for transforming data from one type to another. Any chance anyone knows what it is... it is just on the tip of my tongue!
{
"friends": {
"Charlie": {
"gender": "female",
"age": "28"
},
"Josh": {
"gender": "male",
"age": "22"
},
"Annie": {
"gender": "female",
"age": "24"
}
}
}
In JavaScript the order of Object properties is not guaranteed (ECMAScript Third Edition (pdf):)
4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive
value, object, or function. A function stored in a property of an
object is called a method.
If the order doesn't have to be guaranteed you could do the following:
var t = {
"friends": {
"Charlie": {
"gender": "female",
"age": "28"
},
"Josh": {
"gender": "male",
"age": "22"
},
"Annie": {
"gender": "female",
"age": "24"
}
}
};
// Get all the keys in the object
var keys = Object.keys(t.friends);
// Get the index of the key Josh
var index = keys.indexOf("Josh");
// Get the details of the next person
var nextPersonName = keys[index+1];
var nextPerson = t.friends[nextPersonName];
If order matters I would recommend having another array of to hold the order of the names ["Charlie", "Josh", "Annie"] instead of using Object.keys().
var t = ...;
// Hard code value of keys to make sure the order says the same
var keys = ["Charlie", "Josh", "Annie"];
// Get the index of the key Josh
var index = keys.indexOf("Josh");
// Get the details of the next person
var nextPersonName = keys[index+1];
var nextPerson = t.friends[nextPersonName];
A webservice returns this JSON below
[
{
"companyuserId": "2",
"name": "mike jones",
"superiorname": null,
"departmentId": "26",
"departmentname": "Design",
"companyId": "06",
"UDID": "8df912053a16ab2b4c66a",
"isActive": "1",
"devicetoken": "e8a4c1fad76b45d918f6745bfe60d32a81504",
"email": "mike#yahoo.co.uk",
"phone": "5456465465654"
}
]
Thought it would be straight forward
name = data.name;
phone = data.phone;
email = data.email;
departmentname = data.departmentname;
companyId = data.companyId;
But I'm getting undefined, How else can I do this? I think maybe the data maybe in string format because when I alert data I get the result as pasted above rather than object: Object
That is an array of Objects.. And the Object is the First item inside an array.. So you need to use the index to access the object inside it..
So instead of name = data.name; try this name = data[0].name;
name = data[0].name;
phone = data[0].phone;
email = data[0].email;
departmentname = data[0].departmentname;
companyId = data[0].companyId;
Your JSON object is an array of objects, so it has to be accessed with fully qualified name.
Try this:
name = data[0].name;
phone = data[0].phone;
email = data[0].email;
departmentname = data[0].departmentname;
companyId = data[0].companyId;