将字符串转换为 JSON 对象 [英] Converting a string to JSON object

查看:58
本文介绍了将字符串转换为 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何让 JS 认为一个字符串是 JSON ?

How do you make JS think that a string is JSON ?

我有一个函数,它只在 JSON 对象传递给它时才起作用.如果我向它传递一个字符串,格式与 JSON 相同,则它不起作用.所以我想让这个函数认为传递给它的字符串是一个 JSON.字符串确实是JSON格式.

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

我也尝试了以下方法.我通过 Ajax 输入字符串,handle as"参数为JSON",然后当我将结果传递给函数时,它起作用了.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.

所以我推断问题不在于字符串.如何将此字符串转换为 JSON?如果我通过 ajax 请求获得相同的字符串,然后将其传递给函数工作,而直接传递它不起作用.

So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.

字符串如下:

  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..

推荐答案

var obj = JSON.parse(string);

其中 string 是您的 json 字符串.

Where string is your json string.

这篇关于将字符串转换为 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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