我将数据发布到服务器,结果就是这样。 我想使用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
有人能指出我正确的方向吗?
答案 0 :(得分: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"}"
这是你需要的吗?
答案 1 :(得分:1)
似乎最好的方法可能是解析该字符串(在\ r \ n上拆分)然后将其拆分为=符号并将它们放入正确的JSON格式。添加链接以供参考。