普通网友 2014-12-16 13:14
浏览 141
已采纳

来自文本文件的多个JSON对象

Hello i'm trying to use mutiple json objects as shown in example below.

[
  {
    "DateandTime" : "1025",
    "LoggingLevel" : "ERROR",
    "Description" : "Test"
  }
]
[
  {
    "DateandTime" : "1025",
    "LoggingLevel" : "ERROR",
    "Description" : "Test"
  }
]

This is how it's created from the iOS side because i only create one of the objects at a time because it's for a report logging system and only need a message to be passed when it's needed. So the Json objects are created at separate times and appended to a file.

I know a valid Json string would look like this below.

[
  {
    "DateandTime" : "1025",
    "LoggingLevel" : "ERROR",
    "Description" : "Test"
  },

  {
    "DateandTime" : "1025",
    "LoggingLevel" : "ERROR",
    "Description" : "Test"
  }
]

However that's not what i need. Is there a way of using the two separate Json Objects?

iOS

    NSString *DataString = [NSString stringWithFormat:@"{ \"DateandTime\":\"%@\", \"Description\":\"%@\", \"LoggingLevel\":\"%@\" }", @"1025", logString, [self getLogTypeName:(LOGS)level]];
    NSMutableArray *CurrentData = [NSJSONSerialization JSONObjectWithData:[DataString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray *ArrayOfData = [[NSMutableArray alloc] init];
    [ArrayOfData addObject:CurrentData];
    NSData *JsonObject = [NSJSONSerialization dataWithJSONObject:ArrayOfData options:0 error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:JsonObject encoding:NSUTF8StringEncoding];

    post = [NSString stringWithFormat:@"Message=%@", jsonString];

PHP

$file = 'testingFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
if (isset($_POST['Message'])) {
// Append a new person to the file
$current .= $_POST['Message'] . PHP_EOL; 
// Write the contents back to the file
file_put_contents($file, $current);

} else {
    $Contents = file_get_contents($file);
    echo $Contents;
}

Javascript

function GetLoggingData() {
  $.get("../ISOSEC/logging/TestPHP.php", function(data){
      $.each($.parseJSON(data), function(idx, obj) {
         console.log(obj.DateandTime);
         console.log(obj.LoggingLevel);
         console.log(obj.Description);
         AddLog(obj.DateandTime, obj.LoggingLevel, obj.Description);
      });

  });
}

Could anyone show me how i could merge the objects together if there is already a json object in the file or is there any other work around?

Thanks.

  • 写回答

2条回答 默认 最新

  • dpcyx08288 2014-12-16 13:43
    关注

    As I mentioned in my comment, you would be better off generating a file with valid JSON rather than trying to parse your own JSON syntax.

    You can do this by parsing the existing JSON and appending the objects as needed.

    Conceptual (not tested) example:

    NSMutableArray *currentData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers errors:&errors];
    [currentData addObject:newObject];
    NSData *updatedJSONData = [NSJSONSerialization dataWithJSONObject:currentData options:0 errors:&errors];
    

    Update

    Okay, so as far as I see your question, you have two environments. You have the client and the server. What I didn't catch is that the individual log messages are handled by your PHP script.

    Here's what I would do in your app:

    NSError *error;
    
    // Simplify the generation of your dictionary
    NSDictionary *logLine = @{
        @"DateandTime": @"1024"
        @"Description": logString,
        @"LoggingLevel": [self getLogTypeName:(LOGS)level]
    };
    
    // Create JSON string from dictionary
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:logLine options:0 error:&error];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    // Now post jsonStr as the HTTP body to your PHP script
    

    And this is what I would do in your script:

    <?php
    
    $logFileName = 'testingFile.txt';
    
    // Read your current log file contents
    $currentLogJSON = file_get_contents($logFileName);
    
    // Check the log for any contents
    if (empty($currentLogJSON)) {
        $currentLog = [];
    } else {
        $currentLog = json_decode($currentLogJSON);
        // Ensure that the contents of the log file is an array
        if (is_array($currentLog)) {
            $currentLog = [];
        }
    }
    
    // Get the new log line from HTTP body
    $newLogLineJSON = file_get_contents('php://input');
    // Decode the log line which is passed as JSON string
    $newLogLine = json_decode($newLogLine);
    if (json_last_error() == JSON_ERROR_NONE) {
        // Append the log line to the current log
        $currentLog[] = $newLogLine;
        // Write the updated log contents to log file
        file_put_contents($logFileName, json_encode($currentLog));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示