I have a object in this format
{"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"}
Which is not easily readable is there any way i can clean this object and see like this
business_name: Sport Devy
name: hong kong
I just want to clean the object and convert it into representable form
You could write a function to transform it into the format you want. I am not sure if you specifically want it as a string or as a different object. I am outputting a string but you could modify this to return an object if that is what you need.
function formatDisplay(obj) {
const bname = obj.business_name;
const customer = JSON.parse(obj.customer || "{}");
const name = customer && customer.name;
/* If you need object:
return {
business_name: bname,
name: name
};
*/
return [
"business name: "+ bname,
"name: " + name,
].join("\n");
};
const data = {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"};
console.log(formatDisplay(data));
const obj = {
"paymethod_id": 1,
"business_id": 76,
"delivery_type": "1",
"driver_tip": 0,
"delivery_zone_id": 6569,
"delivery_datetime": null,
"location": {
"lat": 18.7675049,
"lng": -103.1445221
},
"deliveryOptionmodal": {
"id": 3,
"value": "Sin contacto/Dejar orden en la puerta",
"$$hashKey": "object:272"
},
"delivery_cost_new": 10,
"products": {
"name": "Product"
},
"customer_id": 35,
"customer": "{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"hongkongpide#gmail.com\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}",
"business_name": "Soporte Devy"
}
business_name can be read directly from the object - obj.business_name. customer node needs to parsed into javascript object; for that you can use JSON.parse(obj.customer)
Related
I am a beginner, I want to replace spaces with hyphen from keys of JavaScript dictionary and get the keys back in dictionary
eg. In nameVars = {"my name is":"aman", "age":22, "my ed":"btech"}
I want resultant dictionary to be, nameVars = {"my-name-is":"aman", "age":22, "my-ed":"btech"} I am doing it using
for(const [key, value] of Object.entries(nameVars)){
key.replace(/\s+/g,"-")`
}
But my output is still same keys are not changing, please help I don't know JavaScript.
Can someone tell what changes to make if instead this it is in format
topicMessage = { topic: 'some_topic', messages: [{ 'myKey': '{"data": {"my name is ":"aman", "age": 22, "my ed": "btech"}, "meta": {"myAge":24, "school":"aps"}}' }, { 'myKey2': '{ "data": { "my name is 2": "aman", "age": 22, "my ed 2": "btech" }, "meta": { "myAge2": 24, "school": "aps" } } ' }, { "myKey3": '{"data": {"my name is 3":"aman", "age": 22, "my ed 3": "btech"}, "meta": {"myAge":24, "school":"aps"}}' } ] }
here inside messaages of topicMessages in data part we have to make keys dash separated, and value for mykey, mykey2, mykey3 are in string form, so need to convert JSON.parse to object first and then again convert it back to string.
You should replace the content of the Object
var nameVars = {"my name is":"aman", "age":22, "my ed":"btech"}
for (const [key, value] of Object.entries(nameVars)) {
if(key.includes(" ")){
const newKey = key.replace(/\s+/g,"-")
nameVars[newKey] = value;
delete nameVars[key]
}
}
You modify the names of the keys but never add the modified keys back to to the object. You can approach your problem like this:
for(const [oldKey, value] of Object.entries(nameVars)){
const newKey = oldKey.replace(/\s+/g,"-");
// add the entry with the new key
nameVars[newKey] = value;
// delete the old entry
delete nameVars[oldKey];
}
I'm having trouble going through the data because of the ID 29450 and 3000 in this JSON data sample. My whole database has 1500 ID's. Now I want to print the data ['Id', 'Description', 'StartDate'] in the log from both ID's.
I'm a bit stuck now so hopefully somebody can help on the right track.
Thank you in advance. :)
const { Parser } = require('json2csv');
var fs = require('fs');
var fields = ['Id', 'Description', 'StartDate'];
var data = [
{
"29450": {
"Id": "29450",
"Description": "Lasser Niveau 4",
"StartDate": "0001-01-01T00:00:00",
"EndDate": "0001-01-01T00:00:00",
"Company": "",
"ResponsibilityCenter": "",
"FunctionGroup": "",
"City": "",
"Territory": "",
"Country": "",
"Attributes": {
"Name": {
"Description": "",
"Name": ""
},
"WERKTIJDEN": {
"Description": "Anders",
"Name": "Werktijden"
}
},
"RequestNo": ""
},
"3000": {
"Id": "3000",
"Description": "Lasser Niveau 4",
"StartDate": "0001-01-01T00:00:00",
"EndDate": "0001-01-01T00:00:00",
"Company": "",
"ResponsibilityCenter": "",
"FunctionGroup": "",
"City": "",
"Territory": "",
"Country": "",
"Attributes": {
"Name": {
"Description": "",
"Name": ""
},
"WERKTIJDEN": {
"Description": "Anders",
"Name": "Werktijden"
}
},
"RequestNo": ""
},
];
const json2csvParser = new Parser({fields, unwind: ['Id','Description','StartDate'], unwindBlank: true });
const csv = json2csvParser.parse(data);
fs.writeFile('file.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
Expected output:
Instead of...
const csv = json2csvParser.parse(data);
...use...
const csv = json2csvParser.parse(Object.keys(data[0]).map(key => data[0][key]));
Full explanation
Your data is in a strange format. It's an array of one object. I'm not sure if there would ever be another object in the array, but I have to assume that there won't be. So data[0] is the only relevant object here.
This data[0] is what I would call a index. It is an object that has properties that are the primary keys of the objects contained within. It's useful because you can access data[0]['1234'] to obtain the object with id '1234' in constant time. It's not clear if it would ever contain any other properties, but again, I'll assume that it won't because it looks a lot like an index.
You want to begin by getting all the keys of that one-and-only object of interest with Object.keys(data[0]). If you just map these keys to an array of the value of those properties, then you turn the index back into an regular unindexed array of objects -- and this is what json2csv expects as input.
The meat of the fix is a technique like this:
let unindexed = Object.keys(indexed).map(key => indexed[key])
It essentially turns this kind of structure...
var indexed = {
"29450": {
"Id": "29450",
"Description": "Lasser Niveau 4"
},
"3000": {
"Id": "3000",
"Description": "Lasser Niveau 4"
}
};
...into this kind of structure...
var unindexed = [
{
"Id": "29450",
"Description": "Lasser Niveau 4"
},
{
"Id": "3000",
"Description": "Lasser Niveau 4"
}
];
I think your problem is that you want to access the object but don't know its Id. You'll have to define how the object is to be distinguished from any other allowable properties in the containing object. Here's an example that just uses the first key as the one that specifies the object.
Note, this code is intended to be run in a node.js environment and requires the json2csv package npm i json2csv --save
const { Parser } = require('json2csv');
var fs = require('fs');
var fields = ['Id', 'Description', 'StartDate'];
var data = [
{
"29450": {
"Id": "29450",
"Description": "Lasser Niveau 4",
"StartDate": "0001-01-01T00:00:00"
},
"RequestNo": ""
},
{
"3000": {
"Id": "3000",
"Description": "Lasser Niveau 4",
"StartDate": "0001-01-01T00:00:00"
},
"RequestNo": ""
}
];
function getContainedObjectId(container) {
return Object.keys(container)[0];
}
var flattened = data.map(container => container[getContainedObjectId(container)]);
const json2csvParser = new Parser({ fields, unwind: ['Id', 'Description', 'StartDate'], unwindBlank: true });
const csv = json2csvParser.parse(flattened);
fs.writeFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('file saved');
});
Here we rely on the ID being the first key. You'll have to define for us how to distinguish the ID from any other properties that may exist.
Here's another way that is potentially more robust. Search for the first key that looks like an integer (consists of digits 0-9) whose property name matches its value's Id property.
function getContainedObjectId(container) {
return Object.keys(container).filter(key => /^[0-9]+$/.test(key) && container[key].Id === key)[0];
}
This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 3 years ago.
I have one JSON Object and I want to create subset of JSON with particular keys values.
JSON Object
{
"Checksum": "OK",
"ID": "012B4567",
"DOB: "12-12-1991"
"Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
"issue: "11-April-2015",
"DocID": "PASSPORT",
"Number: "123456789",
"Document": "PASSPORT",
"Photo": "Qk06AAAAAAAAA",
"ExpiredFlag": false,
"ExpiryDate": "01 Apr 12",
"Forename": "IMA Phoney",
"Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"ImageSource1": 0,
"Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I want subset from above like below:
{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I have tried below code. It is working fine, But I am not able to understand. I need simplest way:
var data={
"CDRValidation": "CDR Validation test passed",
"AirBaudRate": "424",
"ChipID": "012B4567",
"BACStatus": "TS_SUCCESS",
"SACStatus": "TS_NOT_PERFORMED",
"Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
"DocType": "PASSPORT",
"DocNumber": "123456789",
"DocID": "PASSPORT",
"Surname": "Person",
"Forename": "IMA Phoney",
"SecondName": "J",
"Nationality" : "Imaging Automation Demo State",
"Sex": "Male",
"DOB": "12 May 70",
"ExpiryDate": "01 Apr 12",
"IssueState": "Passport Agency Billerica",
"ExpiredFlag": false,
"ImageSource": 0,
"OptionalData1": "123456789123456",
"OptionalData2": "",
"DateOfIssue":"11 April 02",
"PlaceOfBirth":"Illinois, U.S.A"
}
console.log("----------------->",data);
var Fields = ({
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data, {
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
})
console.log("--------subset--------->",Fields);
There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
const obj = {};
for (let i = 0, length = keys.length; i < length; i += 1) {
obj[keys[i]] = parentObj[keys[i]];
}
return obj;
}
Or you can also use the above code with some functional programming
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
return keys.reduce((acc, key) => ({
...acc,
[key]: parentObj[key];
}), {});
}
A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.
// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);
var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];
var result = propertiesToUse.reduce(function(result, key) {
return result[key] = original[key], result;
}, {});
console.log(result);
What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.
This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data
Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
}
When combined you get the desired result in a single statement.
I'm asking here as I can see this website the most one can help in this
I have an output value in JASON format as the following:
{
"total": 16,
"members": [{
"id": 4,
"name": "Blade11",
"descriptors": {
"os": "Windows 2012 / WS2012 R2"
},
"FCPaths": [{
"wwn": "50060B0000C27208",
"hostSpeed": 0
}, {
"wwn": "50060B0000C2720A",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 11,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 11\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}, {
"id": 6,
"name": "Blade4",
"descriptors": {
"os": "VMware (ESXi)"
},
"FCPaths": [{
"wwn": "50060B0000C27216",
"hostSpeed": 0
}, {
"wwn": "50060B0000C27214",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 8,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 8\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}
what I want is, to parse this output for retrieving an output parameter with the name object only in a list or array of string
for example Names = Blade11, Blade4,....
if you can see in the Json output we have all the names under "members", then each one is another array of values, I want to retrieve only names
thanks
If this JSON is string first you have to parse it
var json = JSON.parse('here is your JSON string');
Than you can access to it properties like you work with object
var names = json.members.map(function(member) {
return member.name;
});
Since you already have JSON format, you can use an array method on the member key of your JSON object to iterate through each array item.
var names = [];
object_name.members.forEach((arrItem) => {
names.push(arrItem.name);
}
or
namesArray = object_name.members.map((arrItem) => {
return arrItem.name;
}
You could use Array#map for iterating all elements of the array and return only the name property.
If you have a JSON string, you need to parse it in advance for getting an object, like
object = JSON.parse(jsonString);
var jsonString = '{"total":16,"members":[{"id":4,"name":"Blade11","descriptors":{"os":"Windows 2012 / WS2012 R2"},"FCPaths":[{"wwn":"50060B0000C27208","hostSpeed":0},{"wwn":"50060B0000C2720A","hostSpeed":0}],"iSCSIPaths":[],"persona":11,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 11\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false},{"id":6,"name":"Blade4","descriptors":{"os":"VMware (ESXi)"},"FCPaths":[{"wwn":"50060B0000C27216","hostSpeed":0},{"wwn":"50060B0000C27214","hostSpeed":0}],"iSCSIPaths":[],"persona":8,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 8\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false}]}',
object = JSON.parse(jsonString),
array = object.members.map(function (a) { return a.name; });
console.log(array);
I'm having some problems when trying to retrieve values from a JSON response sent via the $.post() method in jQuery. Here is the script:
var clickedName = $('#customerId').val();
$.post("/customer-search", { name: clickedName }).done( function(response) {
var results = $.parseJSON(response);
console.log(results);
$('#account-name').html(results.firstname + ' ' + results.lastname);
$('#email').html(results.email);
$('#telephone').html(results.telephone);
if (results.fax) {
$('#fax').html(results.fax);
} else {
$('#fax').html('n/a');
}
$('#personal').fadeIn();
return false;
});
Just to explain, I'm using twitter typeahead in a Symfony2 project, and basically this script will fire when a name is clicked (selected) from the list after typing. The customer-search URL runs a search of the database as follows:
$q = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository('AppBundle:Oc73Customer')->findLikeName($q);
$addresses = $em->getRepository('AppBundle:Oc73Address')->findByCustomerId($customer[0]['customerId']);
$results = array();
$results['customer'] = $customer;
$results['addresses'] = $addresses;
return new Response(json_encode($results));
Which will successfully return a Json encoded response, and the value of 'response' which is printed in the console (as per the jquery above) is:
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
I am trying to retrieve the customer details by using the method I always use, so to get the firstname, I use results.firstname where results is a parsed JSON string, as written in my jQuery response.
However, all I get from results.firstname is undefined, even when it clearly is defined. So, basically, I'm wondering what I am doing wrong?
Hope someone can shed some light on my problem.
The properties you're trying to access are objects in the customer array, not on the parent object itself. Assuming that the response only ever contains one customer object then you can use result.customer[0], like this:
$.post("/customer-search", { name: clickedName }).done(function(response) {
var results = $.parseJSON(response);
var customer = response.customer[0];
$('#account-name').html(customer.firstname + ' ' + customer.lastname);
$('#email').html(customer.email);
$('#telephone').html(customer.telephone);
$('#fax').html(customer.fax ? customer.fax : 'n/a');
$('#personal').fadeIn();
});
If it's possible that multiple customer objects will be returned in the array the you would need to amend your code to loop through those objects and build the HTML to display them all - without using id attributes.
I was able to access it like "results.customer[0].firstname"
var cus =
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
alert(cus.customer[0].firstname);