2015-04-17 102 views
-4

我发布数据到服务器,它变成这样。 我想使用JavaScript将其转换为JSON。如何将这些数据转换为使用JavaScript的JSON?

country=Philippines\r\n 
countryid=840\r\n 
operator=Globe Telecom Philippines\r\n 
operatorid=246\r\n 
connection_status=100\r\n 
destination_msisdn=639358661725\r\n 
destination_currency=PHP\r\n 
product_list=25,50,150,300,500,1000\r\n 
retail_price_list=0.70,1.40,4.10,8.10,13.50,27.00\r\n 
wholesale_price_list=0.56,1.10,3.26,6.49,10.80,21.58\r\n 
authentication_key=1429269579325\r\n 
error_code=0\r\n 
error_txt=Transaction successful\r\n 

任何人都可以指向正确的方向吗?

回答

4

试试这个:

function string_to_json(s) { 
    return JSON.stringify(s.split('\r\n'). 
    reduce(function(s,a) {r = a.split('=', 2); 
    s[r[0]] = r[1]; return s;}, {})) 
} 

用法:

string_to_json("country=Philippines\r\ncountryid=840\r\noperator=Globe Telecom Philippines\r\noperatorid=246\r\nconnection_status=100\r\ndestination_msisdn=639358661725\r\ndestination_currency=PHP\r\nproduct_list=25,50,150,300,500,1000\r\nretail_price_list=0.70,1.40,4.10,8.10,13.50,27.00\r\nwholesale_price_list=0.56,1.10,3.26,6.49,10.80,21.58\r\nauthentication_key=1429269579325\r\nerror_code=0\r\nerror_txt=Transaction successful\r\n") 

输出:

"{"country":"Philippines","countryid":"840","operator":"Globe Telecom Philippines","operatorid":"246","connection_status":"100","destination_msisdn":"639358661725","destination_currency":"PHP","product_list":"25,50,150,300,500,1000","retail_price_list":"0.70,1.40,4.10,8.10,13.50,27.00","wholesale_price_list":"0.56,1.10,3.26,6.49,10.80,21.58","authentication_key":"1429269579325","error_code":"0","error_txt":"Transaction successful"}" 

这是你需要什么?

+0

这个。这是我所说的,但写出来的。 – Nived

1

看起来像你最好的方式可能是解析该字符串(分割\ r \ n),然后将其拆分为=符号并将它们放入正确的JSON格式。添加链接以供参考。

http://www.w3schools.com/js/js_json.asp

相关问题