Reshape JSON array in to single JSON - javascript

I have following JSON array in my code
jsonList = [{"catName":"Carrom"}, {"catName":"Rugby"}]
In my case I want it to be look like this as a single JSON
{ "catName": "Carrom", "catName": "Rugby" }
How can I convert the abov JSON array to a single JSON ? What is the best way to do it ?

Maybe keep as an array of objects and use lodash to filter?
var catArray = [{"catName":"Carrom"}, {"catName":"Rugby"}];
_.find(catArray, { 'catName': 'Carrom' });
This will return any elements that match that query.

Maybe this could work for you
// Do this for every json
var attributes = Object.keys(json1)
for (var i = 0; i < attributes.length; i++) {
jsonresult[attributes[i]] = json1[attributes[i]]
}

According to the above comment by #JohannesReuter I changed my $match as follows now it works fine.
Thanks everyone for the help
Change in my api
`"$match": {
"category": { "$elemMatch": { "catName": { "$in": ["Chess", "Rugby"] } }
},
}`
Now I'm converting my json to this ["Chess", "Rugby"]

Related

JSON Object many errors. Help out

I have made a JSON object and getting so many errors. I am new to JSON so kindly help. Posting here with the screenshots.
Any help would be appreciated.
[![var data\[\]= {"cars":
"Honda":\[
{"model":"Figo" },
{"model":"City"}
\],
"Audi": \[
{"model":"A6"},
{"model":"A8"}
\]
}
data.cars\['Honda'\]\[0\].model
data.cars\['Honda'\]\[1\].model
data.cars\['Audi'\]\[0\].model
ata.cars\['Audi'\]\[1\].model
for (var make in data.cars) {
for (var i = 0; i < data.cars\[make\].length; i++) {
var model = data.cars\[make\]\[i\].model;
alert(make + ', ' + model);
}
}][1]][1]
Using JSONformatter and validator site for checking my code.
Since you mentioned
I am totally novice for JSON
I would like to explain you this completely.
There are little bit of syntax errors in the way you are doing this. You are actually doing a for loop inside a javascript object which will obviously break. If your intention is to alert all the models of all the make, then here is how you do it..
initially you have this
var data = {
cars:{
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
}
You have a variable called data which is a object ({} refers to object) and this object has a property called cars and this property holds a object({} refers to object). Now this object has 2 properties Honda and Audi. Each of this properties are of type array ([] refers to array). And this each array further contains list of objects.
So once you are clear with the above point. Let manipulate the object you have.
Do a forloop to get all the properties of the cars object and when we have hold of each property lets loop its array and then extract the model property value.
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
alert(make + ', ' + model);
}
}
Also dont get confused with Javascript Object and JSON....
In the above example the variable data is Javascript Object and when you do JSON.strinfigy(data) you are converting this Javascript object into string format and that string format is called JSON...
A Demo Fiddle to help you understand better.
Imho it's more like :
var cars = {
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
If you want a huge JSON object storing many cars attributes arrays.
Why do you use these "/" everywhere ?
(PS : if you wanna see some examples -> http://json.org/example.html)
I believe this is the structure your looking for:
cars={
make:{
honda:[
{
model:"accord",
color:"black",
cylinders: "6",
year:"2012"
},
{
model:"civic",
color:"white",
cylinders: "4",
year:"2015"
}
],
acura:[
{
model:"integra",
color:"red",
cylinders: "4",
year:"1992"
},
{
model:"RSX",
color:"Metallic Blue",
cylinders: "4",
year:"2016"
}
],
audi:[
{
model:"R8",
color:"white",
cylinders: "8",
year:"2015"
},
{
model:"A8",
color:"red",
cylinders: "8",
year:"2016"
}
]
}
};
document.addEventListener('DOMContentLoaded',()=>{
var models=[],colors=[],cylinder=[],year=[]; //INSTANTIATE ARRAYS
for(p in cars.make){ //LOOP THROUGH OBJECT PROPS (CARS.MAKE)
cars.make[p].forEach((o)=>{ //LOOP THROUGH (CARS.CARS.PROPS) PUSH OBJ INTO ARRAYS
models.push(o.model);
colors.push(o.color);
cylinders.push(o.cylinders);
year.push(o.year);
});
console.log(models);
console.log(colors);
console.log(cylinders);
console.log(year);
});

Looping through JSON returning values

I've json which looks little complex array of json, I want to parse "1238630400000" and "16.10", like this I need all the values. I'm not getting how we can parse all these values.
This is the code I've tried but no luck:
for (var key in myJSON.Stocks) {
alert(myJSON.Stocks[key].stockPrice);
}
var myJSON = {
"Stocks": {
"stockPrice": [
[1238630400000, 16.10],
[1238716800000, 16.57],
[1238976000000, 16.92],
[1239062400000, 16.43],
[1239148800000, 16.62],
[1239235200000, 17.08],
[1239580800000, 17.17],
[1239667200000, 16.90],
[1239753600000, 16.81],
[1239840000000, 17.35],
[1239926400000, 17.63],
[1241049600000, 17.98]
]
}
}
Can someone help how can i get all these values?
You can get the values by doing a simple forEach on the stockPrice array
myJSON.Stocks.stockPrice.forEach(function(data) { console.log(data[0], data[1]); });
Here is the simplest way:
var csv = myJSON.Stocks.stockPrice.map((o)=>o.join()).join();
console.log(csv);

jQuery getJSON print array where name is string

I have some good practice with using php and mysql, and am now starting with JSON.
I've made a simple json index containing paths to folders, and items inside them:
{ "foldery" : [
{
"foName": "website/img/bg",
"files" : [
"website/img/bg/bg1.jpeg",
"website/img/bg/bg2.jpg",
"website/img/bg/bg3.jpg",
"website/img/bg/bg4.jpeg"
]
},
{
"foName": "website/img/post1",
"files" : [
"website/img/post1/a.jpeg",
"website/img/post1/b.jpg",
"website/img/post1/c.jpeg",
"website/img/post1/d.jpg"
]
}
]
}
Now here is my jquery, for now returning a big mess of data, somewhere including the info about the contents inside:
$.getJSON("nameindex.json", function(data) {
console.log(data);
});
What I would like it to do, in mySql looks like this:
SELECT files FROM foldery WHERE foName = "website/img/post1"
Thus the result, would be an array containing all the files inside post1.
Unfortunately tho, after 2 hours of attempts I have nothing more than the simple console.log code.
Any help would be gladly appreciated
You need to iterate over your array and check forName to equality
function select(o, foName) {
var length = o.foldery.length;
for(var i = 0; i < length; i++){
if (o.foldery[i].foName == foName) {
return o.foldery[i].files;
}
}
}
var result = select(o, "website/img/post1")
console.log(result);
Result
[ 'website/img/post1/a.jpeg',
'website/img/post1/b.jpg',
'website/img/post1/c.jpeg',
'website/img/post1/d.jpg' ]

Need help in creating Json string in javascript

I am unable to create a Json string in the following format, please help. Where key value pair can be a number:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
var uploaded = new Uploaded();
var str = "*#Hello* i *#am* writing a regexp *#h*";
var re = hash_parser(str);
uploaded.tag_list = new Array;
uploaded.tag_list.tag = new Array;
for(var i = 0; i < re.length; i++)
{
uploaded.tag_list[i] = new Object;
uploaded.tag_list[i].**tag** = re[i];
}
above code is giving in following format:
"tag_list":[{"**tag**":"*#Hello*"},{"**tag**":"*#am*"},{"**tag**":"*#h*"}]
I think maybe you might be confusing JSON with object literal syntax.
Instead of:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
you should just be using normal JS syntax:
var tag_container = { "tag1": "Tag1", "tag2": "Tag2", ..... }
... but it's really hard to tell from your post. If you know anyone who can help you with your English, it really might help me (and others) understand this question better.
The easiest way to convert something into JSON is to use JSON.stringify.
var jsonString = JSON.stringify({ tag_container: { tag1: 'tag1', tag2: 'tag2' }});
stringify is available in all modern browsers. If you wish to support older versions, the JSON2 library is perhaps the best choice as it provides the same API as the official JSON spec.
I think what you're trying to do is something like this:
var reLen = re.length;
uploaded.tag_list = {};
for(var i = 0; i < reLen; i++)
{
uploaded.tag_list['tag' + (i+1)] = re[i];
}
This will output the format you wish to see, i.e.
'"tag_container": {"tag1": "*#Hello*", "tag2": "*#am*", "tag3": "*#h*"}'
Thank you all for the all reply and guide my problem is solved in some other way I am sending json string to cross domain
string = "hi #group1 #group2 *user1 *user2 #fs #ffsd #fsdf";
and generated json string is
{"raw_msg":"hi #group1 #group2 *user1 *user2 #fs #ffsd #fsdf","msg_type":"group","top_msg_id":0,"file_container":{"file1":{"id":"","file_name":"","uri":""},"file2":{"id":"","file_name":"","uri":""}},***"tag_list":["fs","ffsd","fsdf"]***,"link_list":"","image_container":{"image1":{"id":"","name":"Name","uri":""},"image2":{"id":"","name":"Name","uri":""}},"attached_thread":{"thread1":{"title":"","top_id":"","last_id":""},"thread2":{"title":"","top_id":"","last_id":""}},"to_user":["user1","user2"],"to_group":["group1","group2"]}

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories