[英]How to get only particular key value pair from json data and store in variable in node js
我有一個樣本json數據,我需要將其添加到mongodb中的不同集合中。但是我不想要整個json數據。例如,
jsondata=
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
}}
在這個json中,我想要一個集合中的窗口鍵,而另一個蒙哥集合中的圖像鍵。 所以我在想是否可以將鍵值對保存在一個變量中,然后可以將該變量添加到集合中。為此,我正在嘗試每個
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat) {
console.log("entering");
var b=stringdata[exKey].image;
console.log(b);
}
但是我無法獲取圖像關鍵數據,這是正確的方法嗎?有人可以幫我這個忙嗎? 我的預期結果是:在一個變量中,window key的值應保存為json格式。 另一個變量中的圖像和文本鍵值相似。
謝謝。
為什么不簡單地從對象中獲取窗口和圖像作為鍵,如:
var window= jsondata.widget.window;
var image = jsondata.widget.image;
並將它們保存在mongo db中
db.window.insert(window)
db.image.insert(image)
告訴我我是否理解正確。
我沒什么大問題。
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat.widget) {
console.log("entering");
console.log(exKey);
if(exKey === 'image'){
db.image.insert(jsondat.widget[exKey]);
}else if(exKey === 'window'){
db.window.insert(jsondat.widget[exKey]);
}
// or db.getCollection(exKey).insert(jsondat.widget[exKey]);
}
但是我還要補充一點,在MongoDB中不希望使用規范化,您應該使用更多的嵌入方式,因為如果想要整理數據,以后將無法加入集合。 但這是一個普遍的想法,也許在您的需求中您想要不同的集合。
您可以通過多種方式進行操作。
var arr = [];
for(var i in jsondata.widget){
if(typeof(jsondata.widget[i])==='object'){
arr.push(jsondata.widget[i]);
}
};
console.log(arr);
您可以使用unserscore
實用程序庫輕松進行操作
var _=require('underscore');
var arr = [];
_.each(jsondata.widget,function(o){
if(typeof(o)==='object'){
arr.push(o);
}
});
console.log(arr);
現在您可以按索引訪問所有對象
輸出量
[ { title: 'Sample Konfabulator Widget',
name: 'main_window',
width: 500,
height: 500 },
{ src: 'Images/Sun.png', name: 'sun1', hOffset: 250 },
{ data: 'Click Here', size: 36, style: 'bold' } ]
嘗試獲取每個內部鍵的單獨值
var window= jsondata.widget.window;
var image= jsondata.widget.image;
var text= jsondata.widget.text;
編輯
var obj={
"json": {
"window": {
"title": "sample",
"name": "sam"
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250
}
}
}
console.log(obj.json.window)
result-> {title: "sample", name: "sam"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.