简体   繁体   中英

Convert json object to string

I have the following controller:

public function getPrice()
{
    $id = $this->input->post('q');
    $data['price'] = $this->emodel->get_peUniformPrice($id);

    echo json_encode($data);
}

which outputs this:

"{\"price\":[{\"Price\":\"250\"}]}"

How can I make it like 250? My jQuery:

function showPrice(size) {
    $.ajax({
        type: "POST",
        url: "<?php echo site_url('enrollment/getPrice/');?>",
        data: {
            q: size
        },
        success: function(data) {
            $("#txtpeUniform").val(data);
        },
    });
}

The $.ajax method will automatically deserialise the string to an object for you, so you simply need to access the required property. Assuming that you only ever want to retrieve the first price returned in the price array, you can access it directly by index. Try this:

success: function(data) {
    $("#txtpeUniform").val(data.price[0].Price); // = 250
},

I can see that you are using jQuery.. if you want to turn the json object into a javascript object you could do something like

var convertedObject = $.parseJSON($data);
alert(convertedObject.Price);

what this effectively does is converts your Json string into a javascript object which you can reference the properties out of and the get the value from these properties.. let me give you another example

var jsonString = {'Firstname':'Thiren','Lastname':'Govender'};
var jObject = $.parseJSON(jsonString);
console.log(jObject.Firstname) // this will output Thiren.
console.log(jObject.Lastname) // this will output Govender.

modify your code

function showPrice(size) {
    $.ajax({
        type: "POST",
        url: "<?php echo site_url('enrollment/getPrice/');?>",
        data: {
            q: size
        },
        success: function(data) {
            console.log(data); // make sure this is returning something..
            $("#txtpeUniform").val(data);
        },
    });
}

I hope this helps you..

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM