How to convert long string to list of objects - javascript

How can I convert the following into a list of objects with javascript.
data:
{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}
When I do typeof on the data I get string. What I am trying to do is create a list with an entry for every object. I tried JSON.parse but it errors on the commas between the curly braces.Thank you.

For that particular string – comma-separated JSON objects – you can wrap it in array brackets [] and parse it:
var data = `{"_id":{"$oid":"5d96f2d3db90fded9f3fa2d1"},"name":"Audi","price":52642},{"_id":{"$oid":"5d96f2dedb90fded9f3fa2d2"},"name":"Mercedes","price":57127},{"_id":{"$oid":"5d96f304db90fded9f3fa2d3"},"name":"Skoda","price":9000},{"_id":{"$oid":"5d96f368db90fded9f3fa2d4"},"name":"Volvo","price":29000},{"_id":{"$oid":"5d96f370db90fded9f3fa2d5"},"name":"Bentley","price":350000},{"_id":{"$oid":"5d96f378db90fded9f3fa2d6"},"name":"Citroen","price":21000},{"_id":{"$oid":"5d96f37fdb90fded9f3fa2d7"},"name":"Hummer","price":41400},{"_id":{"$oid":"5d96f389db90fded9f3fa2d8"},"name":"Volkswagen","price":21600}`;
var parsed = JSON.parse(`[${data}]`);
Then parsed will be an array of 8 entries:
[
{
"_id": {
"$oid": "5d96f2d3db90fded9f3fa2d1"
},
"name": "Audi",
"price": 52642
},
{
"_id": {
"$oid": "5d96f2dedb90fded9f3fa2d2"
},
"name": "Mercedes",
"price": 57127
},
{
"_id": {
"$oid": "5d96f304db90fded9f3fa2d3"
},
"name": "Skoda",
"price": 9000
},
...

Related

Merge a Product Config JSON with Generic Config JSON- Issue While Merging Arrays inside it

I have 2 different Json files
1: a Deaflut JSON file
2: A Product Based JSON file
I need to merge them together in such a way that if a feature in default is not in a product that needs to be added to product config from default one.
for this merge, I used "lodash.mergewith" https://www.npmjs.com/package/lodash.mergewith.
so this is now taking care of the merge, But the file contains multiple nested JSON arrays inside it.
to handle that there is an option to use a customizer method that can handle array merge as mentioned in the usage of lodash.mergewith. I need a customizer that can find the Label from Deaflut and compare it with the Product if the Product has the same Label value then replace the URL with the Product URL. else if the Label is not in Product config, then use it from default as it is.
Example
Default config.json:-links is an array of this json with path : object►login►options►sections►2►links
"links": [{
"url": "www.google.com",
"label": "Lable1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
Productconfig.json:- links is an array inside this of the path: object►login►options►sections►2►links
"links": [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
]
** after merge mergedconfig.json "Links" need to be like this.**
"links": [{
"url": "www.product1.com",
"label": "Label1"
},
{
"url": "www.product2.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
The main concern is this Array is coming inside a JSON file inside some JSON objects
like eg if the Array is inside links[] it will be in a path like : object►login►options►sections►2►links[]. and this Links Array similarly present inside in some other paths eg: object►register►options►sections►2►links[]
So I need to figure out all the Array like this and for each of the Arrays, I need to perform this action.
Just use Array.map and Array.find:
let links= [
{
"url": "www.google.com",
"label": "Label1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
];
let plinks= [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
];
let results = links.map(lnk=>{
plnk = plinks.find(pl=>pl.label.toLowerCase()===lnk.label.toLowerCase());
return plnk || lnk
});
console.log(results);
for clean access to nested JSON keys you can use ES like this:
let a = {
b: {
c: [1,2,3]
}
};
let {c} = a?.b;
console.log(c);

Underscore.js where() function issue with searching json objects

I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working
var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
res.json(book);
});
it is returning
TypeError: Cannot read property '0' of undefined at position 43
The file has valid json, I have tried
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
which also does not work
There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier
What am I doing wrong?
*EDIT: I tried with industryIdentifiers, but response is [ ]
Don't use industryIdentifiers[1]. You want to search the entire industryIdentifiers array, not a single object.
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: req.params.id})[0];
You also need books[0], since books is also an array.
const booksData = {
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Nested forEach issue

I have two arrays of object, the first array (printers, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
cartridges: [],
},
....
]
The second array (cardridges, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "ECH"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do first is to is to iterate through the first array and and then iterate for all the cardridge available: if a the value customData.brand.value of a cardridge is included inside the array 'compatibility' of a printer, then I have to add this cardridge object inside the cardridges array of this printer. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
printers.forEach((printerItem) => {
const printer = printerItem;
printer.compatibilty.forEach((compatibilityItem) => {
const compatibility = compatibilityItem;
cardridges.forEach((cartridge) => {
if (compatibility === cartridge.customData.brand.value.content) {
printer.cartridges.push(cartridge);
}
});
});
});
What am I doing wrong?
You're accessing the wrong property. It should be cartridge.customData.brandName.value.content, carefully note brandName.value rather than brand.value
Your issue is that you're accessing it by the wrong property - brand and not brandName.
Furthermore, if you're targeting everything but IE, you could simplify your nested for loops to utilize some fancy ES6 array methods.
printers.forEach((p) => {
p.cartridges.push(cartridges.filter((c) => {
const brandName = c.customData.brandName.value.content;
return p.compatibilty.includes(brandName);
}));
});

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Angular only pulling last JSON object

Trying to get all JSON objects in an array. It's only returning the last one.
Here's a sample of my JSON:
{
"manufacturer":{
"name": "manufacturername",
"cameras": [
{
"name": "sdfsdfsd",
"type": "Audio device",
"resolution": "Unknown",
"channels": "1"
}
]
},
"manufacturer":{
"name": "manufacturername2",
"cameras": [
{
"name": "sdfsdf",
"type": "Camera",
"resolution": "720P/1.3MP",
"channels": "2"
},
{
"name": "D12",
"type": "Camera",
"resolution": "1080P/3MP",
"channels": "1"
}
]
}}
It is valid JSON.
Here's how I'm calling it:
//Get Manufacturer data
$http.get('data2.json').success(function(data) {
$scope.maninfo = data;
console.log($scope.maninfo);
});
The actual array is much longer - and it's just returning the last Object for some reason.
What you have is valid JSON, but it doesn't correctly express your intent. "manufacturer" (or "name", or "cameras") isn't a type name, it's a unique key into a collection of named values -- dictionary, map, hash, whatever(1). JSON data structures are just a subset of JavaScript object literal declarations (hence the name: JavaScript Object Notation).
So the example above is not an array, it's two successive value assignments to the "manufacturer" property of the same parent object. The parser is assigning the first one to the "manufacturer" property, then replacing that with the second (and in your original, larger) "array", it's then replacing that with the third, and so on.
The "cameras" properties in the manfacturer objects are properly functioning arrays. Just do the same at the higher level -- something more like this:
{
"manufacturers":
[
{
"name": "manufacturername",
"cameras": [
{
"name": "sdfsdfsd",
"type": "Audio device",
"resolution": "Unknown",
"channels": "1"
}
]
},
{
"name": "manufacturername2",
"cameras": [
{
"name": "sdfsdf",
"type": "Camera",
"resolution": "720P/1.3MP",
"channels": "2"
},
{
"name": "D12",
"type": "Camera",
"resolution": "1080P/3MP",
"channels": "1"
}
]
}
]
}
(1) Dictionary, map, hash -- or "associative array". But I didn't want to call it any kind of "array" in that paragraph, because the whole point is it's not the other kind of array.

Categories