How to split one Json to Multiple Json using Angular 2/lodash - json

I have a json and i want to split each key value pair to new json object.
Input:
tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}]
Expected Result:
tokenItems = [
{"firstname" : "Priya"},
{"from": "21-09-2001"},
{"to": "22-08-2001"},
{"address": "zczxczxczx"}
];

You can achieve to that result without lodash.
Use Object.entries, get the key/values and then use map function to create your desired structure of objects.
const tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}];
const newTokenData = Object.entries(tokenData[0])
.map(([key, val]) => ({ [key]: val }));
console.log(newTokenData);

Why use lodash, Simply you can get this using plan javascript, you need to iterate over the key/value pair for each object like this -
const tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}];
let newArr = []
for (let a in tokenData[0]){
newArr.push({[a]: tokenData[0][a]});
}
console.log(newArr);

Related

Reactjs - How to create a JSON with list Child Object?

I have JSON structure like this
"timebought": "2021-01-01T00:00:00",
"totalCost": 3000.0,
"address": "ABC",
"status": false,
"customersEmail":"nguyenvana#gmail.com",
"orderDetails": [
{
"productId": "A1",
"amount": 5
},
{
"productId": "A2",
"amount": 5
}
]
If I want make a JSON for post, how do i do it? I mean the child object "orderDetails", can you give me an example?
I found out how to do it:
First, make a function return list Child:
function toArr(){
let arr = [];
prodList.forEach((prod) => {
let item ={"id":prod.id,"amount" : prod.quantity};
arr = [...arr,item];
});
console.log(arr);
return arr;}
and then
const body = JSON.stringify({
customersEmail : e.target.email.value,
totalCost : totalCost.current,
status : false,
address: e.target.address.value,
orderDetails: toArr()
});

Add JSON data fields names Angular

I have data with no field names, I would like to append to each row a field name
[
"James Vega",
"23",
"abc#test.com"
],
I want to add the fields to this JSON data, I'm working on Angular 6
[
{ "name": "James Vega" },
{ "Age": 23 },
{ "email": "abc#test.com" }
],
You just use map function to transform the object you want
let arr=
[
[
"James Vega",
"23",
"abc#test.com"
]
];
let arr_transform=arr.map(el=> ({
name:el[0],
age:el[1],
email:el[2]
}));
console.log(arr_transform)
If your order of property would be the same, then it is possible to create a mapping and map it with O(1):
const foo = [
"James Vega",
"23",
"abc#test.com"
];
const mapping = {0: 'name', 1: 'Age', 2: 'email'};
const result = foo.map((el, i) => ({[mapping[i]]: el}));
console.log(result);

getting the error like JSON schema is not correct. Enter specified JSON scehma.,Create an Array of Favorite fruits Object

0
I have the following assessment which is to Create Array of Favorite Food items object in data.json file.
The Array of Objects should have the following fields :
Name
Type
Price
After writing the JSON data, this file should be imported in loopobject.js.
I tried the above request with the below data.json
data.json
"{[{\"Name\":\"Apple\",\"Type\":\"fruit\",\"Price\":123},{\"Name\":\"pizza\",\"Type\":\"italian\",\"Price\":360},{\"Name\":\"burger\",\"Type\":\"mac&cheese\",\"Price\":321},{\"Name\":\"jangri\",\"Type\":\"sweet\",\"Price\":329}]}"
loopObject.js
var json = require('./data.json');
json.forEach(function(object) { console.log(object.Name); });
verify.js
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.array().min(3).has({
Name: Joi.string().required(),
Type: Joi.string().required(),
Price: Joi.number().required(),
});
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
const result = Joi.validate(data, schema);
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, schema, function (err, value) {
if(err==null)
{ console.log("JSON is valid.");
}else{
console.log("JSON schema is not correct. Enter specified JSON scehma.");
}
});
i have tried couple of ways, everything looks good,but don't know where i am doing mistake. Could you please help on this??
The JSON format is not correct, try this one:
data.json
[
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
}
]
The JSON data describes an array, and each element of that array is an object.

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})

How to parse json data using prototype.js and iterate through it?

I have json array like
var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]'
How to parse the the data and iterate through it using prototype.js?
There is a function called evalJSON()
var data = '[{ "name": "Violet", "occupation": "character" },{ "name": "orange", "occupation": "color" }]';
data = data.evalJSON();
//for more security:
data = data.evalJSON(true); //sanitizes data before processing it
Then just use for to iterate through the array:
for (var i=0;i<data.length;i++)
{
//do whatever you like with data[i];
}
Or use the prototypeJS .each() function:
data.each(function(el){
//do whatever you like with el
});