如何转换json文件?

时间:2018-10-03 13:15:04

标签: javascript json reactjs

我有json个文件,但我不知道如何转换。

我正在尝试使用stringilyparse,但是它不起作用。

在下面查看我的json数据:

  first: {
     'big': {
       'letter': 'let',
       'Can go walk': 'CGW',
       'something': 'smthg'
     },
     'low': {
       'call_me': 'call me',
       'just_do_it': 'just do it'
     }
}

我需要将其转换为以下格式:

  first: [{
     big: [
       {name: 'letter', value: 'let'},
       {name: 'Can go walk', value: 'CGW'},
       {name: 'something', value: 'smthg'}
     ],
     low: [
       {name: 'call_me', value: 'call me'},
       {name: 'just_do_it', value: 'just do it'},
     ]
}]

如何将格式1转换为格式2(在此情况下,我将对象转换为格式2并在格式转换为1后进行一些更改

3 个答案:

答案 0 :(得分:0)

JSON标准是使用双引号,JS的JSON.parse()函数现在可以使用单引号。尝试以下方法:

var x = JSON.parse('{"big": {}, "low": {}}')

var arr = [x["big"], x["low"]]

答案 1 :(得分:0)

一种替代解决方案(杂乱无章)

const json = {
 first: {
   'big': {
    'letter': 'let',
    'Can go walk': 'CGW',
    'something': 'smthg'
   },
   'low': {
    'call_me': 'call me',
    'just_do_it': 'just do it'
   }
 }
}
let arr = [{}]
for (let prop_lv0 in json) {
 arr[0][prop_lv0] = [{}];
  for (let prop_lv1 in json[prop_lv0]) {
   arr[0][prop_lv0][0][prop_lv1] = [];
    for (let prop_lv2 in json[prop_lv0][prop_lv1]) {
     arr[0][prop_lv0][0][prop_lv1].push({ name: prop_lv2, value: json[prop_lv0][prop_lv1][prop_lv2] })
    }
   }
 }
console.log(arr)

答案 2 :(得分:-2)

    Jquery cs code:
    
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
            
        
                [WebMethod]
                    public string GetCountry()
                    {
                        string _data = "";
                        con.Open();
                        SqlCommand cmd = new SqlCommand("usp_country_get",con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        con.Close();
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            _data = JsonConvert.SerializeObject(ds.Tables[0]);
                        }
                        return _data;
                    }
            
            [WebMethod]
                    public void Insert(string A, int B, int C, string D)
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("usp_emp_insert", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@name", A);
                        cmd.Parameters.AddWithValue("@cid", B);
                        cmd.Parameters.AddWithValue("@gender", C);
                        cmd.Parameters.AddWithValue("@hobbies", D);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
            
            
            [WebMethod]
                    public void Delete(int ID)
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@id", ID);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
            
            [WebMethod]
                    public string Edit(int ID)
                    {
                        string _data = "";
                        con.Open();
                        SqlCommand cmd = new SqlCommand("usp_emp_edit", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@id", ID);
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        con.Close();
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            _data = JsonConvert.SerializeObject(ds.Tables[0]);
                        }
                        return _data;
                    }
            
            
            [WebMethod]
                    public void Update(int ID, string A, int B, int C, string D)
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("usp_emp_update", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@id", ID);
                        cmd.Parameters.AddWithValue("@name", A);
                        cmd.Parameters.AddWithValue("@cid", B);
                        cmd.Parameters.AddWithValue("@gender", C);
                        cmd.Parameters.AddWithValue("@hobbies", D);
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
            
                [WebMethod]
                        public string GetEmployee()
                        {
                            string _data = "";
                            con.Open();
                            SqlCommand cmd = new SqlCommand("usp_emp_get", con);
                            cmd.CommandType = CommandType.StoredProcedure;
                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            con.Close();
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                _data = JsonConvert.SerializeObject(ds.Tables[0]);
                            }
                            else
                            {
                                _data = JsonConvert.SerializeObject(ds.Tables[0]);
                            }
                            return _data;
                        }






aspx code:

Scripting :

<script src="jquery-3.2.1.js"></script>

    <script type="text/javascript">
        var IDD = "";
        $(document).ready(function () {
            CountryBind();
            //EmployeeBind();
        });

        function CountryBind() {
            $.ajax({
                url:'Employee.asmx/GetCountry',
                type:'post',
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                data:'{}',
                async: false,
                success: function (_dt) {
                    _dt = JSON.parse(_dt.d);
                    for (var i = 0; i < _dt.length; i++) {
                        $("#ddlcountry").append($('<option/>').attr("value", _dt[i].cid).text(_dt[i].cname));
                    }
                },
                error: function () {
                    alert('CountryBind error');
                }
            });
        }


        function SaveData() {
            var HOB = "";
            HOB = $('input:checkbox:checked.B').map(function () {
                return this.value;
            }).get().join(',');
            if ($("#btnsave").val()==("Save")) {
                $.ajax({
                    url: 'Employee.asmx/Insert',
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: 'json',
                    data: "{A:'" + $("#txtname").val() + "',B:'" + $("#ddlcountry").val() + "',C:'" + $('input:radio[name=A]:checked').val() + "',D:'" + HOB + "'}",
                    success: function () {
                        alert('insert success !!');
                        EmployeeBind();
                    },
                    error: function () {
                        alert('insert error !!');
                    }
                });
            }
            else {
                $.ajax({
                    url: 'Employee.asmx/Update',
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    dataType: 'json',
                    data: "{ID:" + IDD + ",A:'" + $("#txtname").val() + "',B:'" + $("#ddlcountry").val() + "',C:'" + $('input:radio[name=A]:checked').val() + "',D:'" + HOB + "'}",
                    success: function () {
                        alert('Update Successfully');
                        EmployeeBind();
                    },
                    error: function () {
                        alert('Update error');
                    }
                });
            }

        }

        function EmployeeBind() {
            $.ajax({
                url: 'Employee.asmx/GetEmployee',
                type: 'post',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: "{}",
                async: false,
                success: function (_dt) {
                    _dt = JSON.parse(_dt.d);
                    $("#tbl").find("tr:gt(0)").remove();
                    for (var i = 0; i < _dt.length; i++) {
                        $("#tbl").append('<tr><td>' + _dt[i].name + '</td><td>' + _dt[i].cname + '</td><td>' + (_dt[i].gender == "1" ? "Male" : _dt[i].gender == "2" ? "FeMale" : "Others") + '</td><td>' + _dt[i].hobbies + '</td><td><input type="button" id="btnedit" value="Edit" onclick="EditData(' + _dt[i].id + ')" /><td><input type="button" id="btndelete" value="Delete" onclick="DeleteData(' + _dt[i].id + ')" /></td</tr>');
                    }
                },
                error: function () {
                    alert('EmployeeBind error');
                }
            });
        }

        function DeleteData(id) {
            $.ajax({
                url: 'Employee.asmx/Delete',
                type: 'post',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: "{ID:'" + id + "'}",
                success: function () {
                    alert('Delete Successfully');
                    EmployeeBind();
                },
                error: function () {
                    alert('DeleteData error');
                }
            });
        }

        function EditData(id) {
            $.ajax({
                url: 'Employee.asmx/Edit',
                type: 'post',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                async:false,
                data: "{ID:'" + id + "'}",
                success: function (_dt) {
                    _dt = JSON.parse(_dt.d);
                    $("#txtname").val(_dt[0].name);
                    $("#ddlcountry").val(_dt[0].cid);
                    $("input[name=A][value=" + _dt[0].gender + "]").prop('checked', true);

                    var hbb = _dt[0].hobbies;
                    var arr = hbb.split(',');
                    $("input:checkbox:checked.B").prop('checked', false);
                    for (var i = 0; i < arr.length; i++) {
                        $("input:checkbox[class=B][value=" + arr[i] + ']').prop('checked', true);
                    }

                    $("#btnsave").val("Update");
                    IDD = id;
                    EmployeeBind();
                },
                error: function () {
                    alert('EditData error');
                }
            });
        }
    </script>

Body:

<body>
    <table>
    <tr>
        <td>Name :</td>
        <td><input type="text" id="txtname" /></td>
    </tr>
        
    <tr>
        <td>Country :</td>
        <td><select id="ddlcountry">
                <option value="0">--Select--</option>
            </select>
        </td>
    </tr>

    <tr>
        <td>Gender :</td>
        <td>
            <input type="radio" name="A" value="1" /> male
            <input type="radio" name="A" value="2" /> female
            <input type="radio" name="A" value="3" /> other
        </td>
    </tr>

     <tr>
        <td>Hobbies :</td>
        <td>
            <input type="checkbox" class="B" value="cricket" /> cricket
            <input type="checkbox" class="B" value="music" /> music
            <input type="checkbox" class="B" value="movies" /> movies
            <input type="checkbox" class="B" value="cooking" /> cooking
            <input type="checkbox" class="B" value="coding" /> coding
        </td>
    </tr>

    <tr>
        <td></td>
        <td><input type="button" id="btnsave" value="Save" onclick="SaveData()" /></td>
    </tr>
</table>

    <table id="tbl" border="1" style="border-color:darkblue;width:100%">
        <tr>
            <th>Name</th>
            <th>Country</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </table>
</body>