[英]how to read JSON file in a customized way
I have a JSON object like below我有一个像下面这样的 JSON 对象
{
"db": {
"name": "db",
"connector": "memory"
},
"MySql": {
"host": "localhost",
"port": 3306,
"database": "users",
"username": "root",
"password": "",
"name": "MySql",
"connector": "mysql"
},
"postgreDS": {
"host": "localhost",
"port": 1234,
"database": "abc",
"username": "postgres",
"password": "abc",
"name": "postgreDS",
"connector": "postgresql"
}
I need the following output from this object.我需要这个对象的以下输出。
{"db", "MySql", "postgreDS"}
how should I extract the above information from whole JSON object in JavaScript.我应该如何从 JavaScript 中的整个 JSON 对象中提取上述信息。 and how I will read the sub keys and there values.以及我将如何读取子键和值。
Something like this (where obj
is your JSON-object):像这样(其中obj
是您的 JSON 对象):
var objectProperties = [];
for(var prop in obj){
objectProperties.push(prop);
}
console.log(JSON.stringify(objectProperties)); // ["db", "MySql", "postgreDS"]
If you're merely looking to get the keys of the nested objects use Object.keys
:如果您只是想获取嵌套对象的键,请使用Object.keys
:
var keys = Object.keys(obj); // [ "db", "MySql", "postgreDS" ]
If you're looking to get the values from within the nested objects based on a specified key here's a generic function that will return an array of values:如果您想根据指定的键从嵌套对象中获取值,这里有一个通用函数,它将返回一个值数组:
function getValueFromKey(obj, key) {
return Object.keys(obj).map(function (el) {
return obj[el][key];
});
}
getValueFromKey(obj, 'name'); // [ "db", "MySql", "postgreDS" ]
getValueFromKey(obj, 'connector'); // [ "memory", "mysql", "postgresql" ]
javascript javascript
$(function(){
var output = {};
var items = {
"db": {
"name": "db",
"connector": "memory"
},
"MySql": {
"host": "localhost",
"port": 3306,
"database": "users",
"username": "root",
"password": "",
"name": "MySql",
"connector": "mysql"
},
"postgreDS": {
"host": "localhost",
"port": 1234,
"database": "abc",
"username": "postgres",
"password": "abc",
"name": "postgreDS",
"connector": "postgresql"
}};
for(var propertyName in items) {
output.push(propertyName); // output will have the required output
}
console.log(output);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.