0

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.

4
  • You have to create valid JSON for a JSON parser to successfully parse it. I am sure you can do some workarounds in the parser side to make it work. But why don't you put your effort into writing proper JSON in the first place? Commented Dec 16, 2014 at 13:18
  • Like @RonniEgeriis said it would be far more easier to read the file check if there is already a json string if there is add the new content then write to that file instead of finding a way to parse this. Commented Dec 16, 2014 at 13:25
  • @RonniEgeriis It's valid JSON if it was only one object like i explained. However i'm not sending all the JSON data at the same time, it's sent at different times because they're logging reports and just appended to the text file. I've updated my question to ask if anyone can show me how to append two objects together or another way around it? Commented Dec 16, 2014 at 13:39
  • @Chris Yes, but it becomes invalid when you start appending data without respecting the JSON syntax. Then you create your own conventions, which can give you a lot of headaches. I suppose you use NSJSONSerialization? Check my answer below. Commented Dec 16, 2014 at 13:45

2 Answers 2

1

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));
}
Sign up to request clarification or add additional context in comments.

6 Comments

It's now in this format - [{"DateandTime":"1025","LoggingLevel":"ERROR","Description":"Test"}] ...However i'm getting the same problem, everytime something get logged it gives me the same problem. [{"DateandTime":"1025","LoggingLevel":"ERROR","Description":"Test"}] [{"DateandTime":"1025","LoggingLevel":"MESSAGE","Description":"Another Time Run"}]
Do you understand my concept? That you read the current content of your log file, parse it to a NSObject, append your new log data and serialize it to JSON data again?
@Chris If you provide your current code in your question, that would be a great help to better illustrate my idea.
I've updated my question with my current code. Hope it's enough for you to better illustrate your idea.
I've tested it and it's giving me [null] in the text file
|
0

If your file will always look like the first example you could very well only make a preg_replace

This is only a subjestion it is probably a bad way of doing it but I think it could work.

Edit

Try this instead

$NewSingleJsonString = preg_replace("/.\].\[.\s+/s",',',$MultipleJsonString);

1 Comment

preg_replace doesn't seem to work, it doesn't replace anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.