首页 > 解决方案 > 如何使用 C++ 仅打印 JSON 文件中的一组特定行?

问题描述

这是 JSON 文件,我需要使用 Mergesort、QuickSort、插入排序等排序算法对每个“Sample”进行排序。我可以处理排序,但我将如何访问“Samples”的值,因为一旦我遍历整个文件,我也会打印我不想要的元数据。我将如何使用 C++ 做到这一点?

{
  "Sample01": [
    1982297351,
    -1401779359,
    -1060884358,
    -526181663,
    512839761,
    1973273930,
    166828894,
    2118330955,
    -1205701654,
    1045410763
  ],
  "Sample02": [
    715111365,
    -1635156980,
    -1275799354,
    390902376,
    -1995120010,
    1079845325,
    -348388581,
    1487669981,
    946977879,
    -114777126
  ],
  "Sample03": [
    1887368688,
    -682665424,
    1115113643,
    -1244318203,
    -1165484372,
    913553810,
    1876752273,
    -1734982866,
    -197632295,
    -809020716
  ],
  "Sample04": [
    47979117,
    -1575893827,
    232070520,
    98942291,
    919917534,
    608798182,
    1098685159,
    2120663610,
    502723784,
    1754098591
  ],
  "Sample05": [
    -1941714245,
    -746761655,
    -194269038,
    -1274094575,
    -534237500,
    330995517,
    -1394100885,
    1843234851,
    -1636524188,
    1849312960
  ],
  "Sample06": [
    1563427224,
    866832458,
    1786768419,
    -1384300751,
    -2115741192,
    1794858015,
    2064677780,
    -569748690,
    201560529,
    1839266408
  ],
  "Sample07": [
    -1493722040,
    -1786039336,
    1929759925,
    16815988,
    -369302171,
    1246192730,
    -1757215234,
    736550370,
    96897197,
    -890156132
  ],
  "Sample08": [
    1380115946,
    2117857206,
    1496245749,
    -156983386,
    714565805,
    966168336,
    211590140,
    771013311,
    1341992631,
    -667519985
  ],
  "Sample09": [
    -1744375925,
    1839741715,
    1811248031,
    1763666372,
    1356783657,
    1175336051,
    260157377,
    956263021,
    915815615,
    1741220797
  ],
  "Sample10": [
    1999949854,
    1889430998,
    -439989550,
    -52691173,
    1466290457,
    845652536,
    1141819606,
    1123606984,
    554052149,
    1152333926
  ],
  "metadata": {
    "arraySize": 10,
    "numSamples": 10
  }
}

标签: c++json

解决方案


It should be pretty straight forward to read this file and parse it using std::ifstream::operator>>

Read char '{'
While true
    Read string name
    If name starts with "\"Sample"
        Read char '['
        While true
            Read number value
            Read char ',' or ']'
            If char is ']'
                Break
    Else
        Read char '{'
        While true
            Read string
            Read number
            Read char ',' or '}'
            If char is '}'
                Break
    Read char ',' or '}'
    If char is '}'
        Break

You store all items that start with "Sample


推荐阅读