普通网友 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 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊