2012-11-22 53 views
0

我从UI获取数据如下,所有下面的输入数据都是字符串。如何将字符串值作为json对象存储在mongo数据库中?

CUST_ID:temp001 cust_chart_id:测试 default_chart:假 chart_pref_json:{范围:6M,CHART_TYPE:烛台,指标:{},周期:每日,futurepadding:20}}

我试图存储mongodb中的chart_pref_json。这chart_pref_json对象实际上是存储在数据库如下字符串,

{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : "{range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20}" }** 

但其实我是想这chart_pref_json存储为如下的JSON对象。

{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} }** 

任何人都可以帮助我解决这个问题。

+0

当我试图保存“chart_pref_json”:{range:6m,chart_type:烛台,指标:{},句号:Daily,futurepadding:20}}在mongodb中,它保存为字符串“{range:6m, chart_type:candlestick,指标:{},期间:Daily,futurepadding:20}“而不是我想要存储为json {范围:6m,chart_type:烛台,指标:{},期:Daily,futurepadding:20} 。 – Sandy

回答

0

在将其设置为应用程序中的字段之前,需要使用您的语言的JSON解码功能将其作为对象进行编码。在PHP中,你会做的是这样的:

$db->collection->insert(array(
    'cust_id' => 'temp001', 
    … your other fields … 
    'chart_pref' => json_decode($varContainingJson) 
)); 

对于Java,下面的例子将帮助:

BasicDBObject obj = JSON.parse(varContainingJson); 

其中在https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/Y3KyG_ZSfJg

相关问题