【问题标题】:Sort JSON by values in MATLAB在 MATLAB 中按值对 JSON 进行排序
【发布时间】:2021-01-11 19:14:42
【问题描述】:

我想按“createdAt”对 JSON 文件顺序中的值进行排序,并在绘图函数中使用这些值。如您所见,此列存储日期值,因此我已对其进行了转换。而且我已经应用了排序功能,但是当我看到数据的输出时,似乎排序不适用。

data = loadjson('C:/data/default.json');
count_data = sum(cellfun(@(x) numel(x),data.Location)); %returns 21

for i=1:count_data
   createdAt= cellfun( @(cellElem) cellElem.createdAt, data.Location ,'UniformOutput',false);
   createdAtDate= datetime(createdAt(i),'InputFormat','dd-MM-yyyy HH:mm:ss','Format', 'dd-MM-yyyy n HH:mm:ss');
    [~,X] = sort(createdAtDate,'descend');
    out=data(X);
end

for i=1:count_data
  x = cellfun( @(cellElem) cellElem.createdAt, out.Location,'UniformOutput',false);
  disp(x);
 end

我的 JSON 文件:

"Location": [
{
  "id": "0b5965e5-c509-4522-a525-8ef5a49dadaf",
  "measureId": "5a6e9b79-dbb1-4482-acc1-d538f68ef01f",
  "locationX": 0.9039769252518151,
  "locationY": 0.2640594070404616,
  "createdAt": "06-01-2021 19:38:44"
},
{
  "id": "18714a2f-a8b3-4dc6-8a5b-114497fa9671",
  "measureId": "671f52bc-a066-494a-9dce-6e9ccfac6c1d",
  "locationX": 1.5592001730078755,
  "locationY": 0.5207689756815629,
  "createdAt": "06-01-2021 19:35:24"
},

提前致谢。

【问题讨论】:

    标签: json matlab sorting matlab-guide


    【解决方案1】:

    你需要提取所有你需要的数据,然后排序

    x = cellfun( @(cellElem) cellElem.locationX, data.Location );
    y = cellfun( @(cellElem) cellElem.locationY, data.Location );
    % Get date strings
    d = cellfun( @(cellElem) cellElem.createdAt, data.Location, 'UniformOutput', false)
    % Convert to datetime
    d = datetime( d, 'InputFormat', 'dd-MM-yyyy HH:mm:ss' );
    % Get the sort order
    [~,idx] = sort( d );
    % Sort other arrays
    x = x(idx);
    y = y(idx);
    

    另一种选择是使用表格

    x = cellfun( @(cellElem) cellElem.locationX, data.Location );
    y = cellfun( @(cellElem) cellElem.locationY, data.Location );
    % Get dates
    d = cellfun( @(cellElem) cellElem.createdAt, data.Location, 'UniformOutput', false)
    d = datetime( d, 'InputFormat', 'dd-MM-yyyy HH:mm:ss' );
    % Create table
    t = table( x(:), y(:), d(:), 'VariableNames', {'locationX','locationY','createdAt'} );
    % Sortrows
    t = sortrows( t, 'createdAt' );
    

    您必须在此处使用表格而不是矩阵(尽管sortrows 可以接受任何一种),因为列之间的数据类型混合。

    【讨论】:

    • 谢谢你,好先生!实际上,我也做过类似的事情,但我只是错过了如何使用排序。
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 2021-09-16
    • 2016-06-05
    • 1970-01-01
    • 2021-06-21
    • 2016-09-21
    • 2014-05-12
    • 2018-07-05
    相关资源
    最近更新 更多