普通网友 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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器