如何在javascript中将JSON数据存储到键值对中?
我有一个json数据文件:data.js 它包含以下数据
[
{ "Sound": "0.550951615" },
{ "Battery": 0.2567320563 },
{ "Screen": 0.0703125 },
{ "RAM": 0.1246117102 },
{ "Connectivity": 0 },
{ "Camera": 0.2721623766 },
{ "Design": 0.3677622768 },
{ "Processor": 0 }
]
如何将这些数据存储在java脚本中的键值对数据结构中?
答案 0 :(得分:1)
您可以使用Array.map
或Array.reduce
(请参阅MDN)将Array元素映射到对象,例如:
var objmap = {}, objred = {};
// parse the string (from your file)
var objFromFile =
JSON.parse('[\
{ "Sound": "0.550951615" },\
{ "Battery": 0.2567320563 },\
{ "Screen": 0.0703125 },\
{ "RAM": 0.1246117102 },\
{ "Connectivity": 0 },\
{ "Camera": 0.2721623766 },\
{ "Design": 0.3677622768 },\
{ "Processor": 0 }\
]');
// and map it to [obj]
var mapped = objFromFile.map(
function (v) { for (var l in v) {this[l] = v[l];} },
objmap
);
// or use reduce if you prefer it
var reduced = objFromFile.reduce(
function(p, n) {
for (var l in n) {p[l] = n[l];}
return p;
},
objred
);
// show the result, using JSON.stringify
document.querySelector('#result').textContent =
'mapped:\n' + JSON.stringify(objmap, null, ' ') +
'\n\nreduced:\n' + JSON.stringify(objred, null, ' ');

<pre id="result"></pre>
&#13;
答案 1 :(得分:1)
JSON表示JavaScript对象表示法。这是用于存储数据的系统语法。
用于存储单个值:
var Object1 = {
"Key": "Value"
}
用于存储多个值:
var Object1 = {
"Key1": "Value1",
"Key2": "Value2",
"Key3": "Value3",
"nth key": "nth value"
}
答案 2 :(得分:1)
您需要处理数据结构以完成此操作。
var a = [
{ "Sound": "0.550951615" },
{ "Battery": 0.2567320563 },
{ "Screen": 0.0703125 },
{ "RAM": 0.1246117102 },
{ "Connectivity": 0 },
{ "Camera": 0.2721623766 },
{ "Design": 0.3677622768 },
{ "Processor": 0 }
]
var keyValue = {}
a.forEach(function(e) {
keyValue[Object.keys(e)[0]] = Object.values(e)[0]
})
console.log(keyValue)
的输出
{"Sound":"0.550951615","Battery":0.2567320563,"Screen":0.0703125,"RAM":0.1246117102,"Connectivity":0,"Camera":0.2721623766,"Design":0.3677622768,"Processor":0}
答案 3 :(得分:0)
var myObject = {
key: value,
key: value
};
你真的只是以那种格式列出你的内容。
答案 4 :(得分:0)
您已将数据存储为键:值。
如果您想知道如何访问数据的各种部分,请查看以下文章:JavaScript loop through json array?
或......
您可以按索引找到特定的k:v对。在您的情况下,如果您将有效负载存储在变量中,您可以像这样访问数据:
var data = [
{ "Sound": "0.550951615" },
{ "Battery": 0.2567320563 },
{ "Screen": 0.0703125 },
{ "RAM": 0.1246117102 },
{ "Connectivity": 0 },
{ "Camera": 0.2721623766 },
{ "Design": 0.3677622768 },
{ "Processor": 0 }
]
data[0]
这将返回{“Sound”:“0.550951615”}
您可以搜索JSON引用的TON资源。
祝你好运!