简体   繁体   English

将 JSON 数组引号替换为括号 [

[英]Replace JSON array quotes with brackets [

I have a JSON array being passed form PHP and it looks like this:我有一个从 PHP 传递的 JSON 数组,它看起来像这样:

[{from: "2019,09,14", to: "2019,09,14"}]

and I need it to look like this:我需要它看起来像这样:

[{from: [2019, 9, 14], to: [2019, 9, 17]}]

here is my code thus far:到目前为止,这是我的代码:

function getPricingDateRanges() { var city = document.getElementById("pricingcityselect").value; function getPricingDateRanges() { var city = document.getElementById("pricingcityselect").value;

$.ajax({
    url: 'getpricingdaterangepicker.php?city=' + city,       // Change this to the uri of your file
    method: 'GET',                 // Use the GET method
    dataType: 'json',              // Expect a JSON response
    success: function(response) {  // What will happen when the request succeeds

        var darray = [{from:[2019,9,14], to:[2019,9,17]}];

        console.log(response);
        console.log(darray);

    }
});

} }

Added code from my PHP:从我的 PHP 添加代码:

<?php
include 'dbconfig.php';

$city = ($_GET['city']);

$sql="SELECT start_date, end_date FROM date_ranges WHERE city='" . $city . "'";
$result = mysqli_query($conn,$sql);

// Create empty array.
$date_ranges = array();

// Add every row to array;
while($row = mysqli_fetch_array($result)) {

    // Create an associative array to store the values in.
    // This will later be a JavaScript Object.

    $from = new DateTime($row['start_date']);
    $ffrom = $from->format('Y,m,d');

    $to = new DateTime($row['end_date']);
    $fto = $from->format('Y,m,d');

    array_push($date_ranges, array(
        'from'   => $ffrom,
        'to'     => $fto
    ));

} 

// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>

First, it's important to point out that the "JSON" you've included is not JSON.首先,重要的是要指出您包含的“JSON”不是JSON。 It is neither a string, nor are the property names quoted.它既不是字符串,也不是引用的属性名称。

However, if this is actually the input you're dealing with, you can loop through the items, split the from and to values on , , and use .map(Number) to convert them to integers.但是,如果这实际上是您正在处理的输入,您可以遍历这些项目,将fromto值拆分为, ,然后使用.map(Number)将它们转换为整数。

 const arr = [{from: "2019,09,14", to: "2019,09,14"}]; //Helper function to split on comma, convert items to numbers const toIntegerArray = str => str.split(",").map(Number); const result = arr.map(({from,to}) => ({ from: toIntegerArray(from), to: toIntegerArray(to) })); console.log(result);

Parse JSON till the point with "2019,09,14" ."2019,09,14"解析JSON直到点。

then "2019,09,14" convert to array of numbers by:然后"2019,09,14"通过以下方式转换为数字数组:

"2019,09,14".split(',').map(el => parseInt(el, 10)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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