如何将String变量用作JSON对象中的键 [英] How to use a String variable as key in a JSON object

查看:215
本文介绍了如何将String变量用作JSON对象中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是一种使用var在密钥中创建JSON对象的方法吗?

我想通过使用(String)变量的值作为键来构造JavaScript中的JSON对象。但我得到的是变量的名称作为键。

I would like to construct a JSON object in JavaScript by using the value of a (String) variable as the key. But what I got is the name of the variable as the key.

example.js:

example.js:

function constructJson(jsonKey, jsonValue){
   var jsonObj = { "key1":jsonValue, jsonKey:2};
   return jsonObj;
}

电话

constructJson("key2",8);

返回JSON - > {key1:8,jsonKey:2}但我会喜欢{key1:8,key2:2}。

returns a JSON -> {"key1":8,"jsonKey":2} but I would like to have {"key1":8,"key2":2}.

有谁知道怎么做到这一点?
似乎是一个简单的问题,但我找不到解决方案

Does anyone know how to achieve this? seems like a simple problem but i cannot find the solution

提前thx,
ronny

thx in advance, ronny

推荐答案

function constructJson(jsonKey, jsonValue){
   var jsonObj = {"key1": jsonValue};
   jsonObj[jsonKey] = "2";
   return jsonObj;
}

这篇关于如何将String变量用作JSON对象中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆