1

Following is the json string which got stored in database column in invalid format as .

{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}


  $variable = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';

so i want to encode & decode it in php so what will be the regular expression where i can convert the invalid json into valid and parse it properly?

thanks in advance.

5
  • too many mistakes Commented Jul 27, 2017 at 10:56
  • validate the json string before saving it to db Commented Jul 27, 2017 at 10:57
  • that is my mistake that i haven't validated that before storing into db. Commented Jul 27, 2017 at 10:59
  • Have you tried something? Commented Jul 27, 2017 at 14:09
  • tried below answers both methods. its working fine for me. thanks Commented Jul 27, 2017 at 16:36

2 Answers 2

2

Is easy to visualize the mistake in your JSON encoding analizing the example provided line. There is a pattern , so it can be recovered easilly.

REGEX approach

You can fix your string aplying a 2 stages regexp, the first one to introduce the missing double quotes, and the second, to inject the coma delimiters.

<?php
$str = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';
$str = preg_replace( '/"\w+":\s"[\w\s]*/' , '$0"' , $str);
$str = preg_replace( '/""/' , '","' , $str);
echo $str;
?>

STRING MANIPULATION approach

Another approach is by deconstruction, splitting the string, processing the parts, and building the object again:

<?php
$str = '{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}';

// remove '{' from the beggining of the string
$str = ltrim($str, '{');
// remove '}' from the end of the string
$str = rtrim($str, '}');
// remove the first '"' from the beggining of the string
$str = ltrim($str, '"');
// split the string in each '"'
$raw = explode('"' , $str);
// prepare an empty array to store valid properties&values
// and store in it the valid keys (removing useless keys ":")
$clean = array();
for ($i = 0; $i < count($raw); $i++) {
  if ( trim( $raw[$i] ) !== ":") array_push( $clean,$raw[$i] );
}
// asumming property names are on odd keys 
// and values in even keys
// we can now create a valid object...
$obj = array();
for ($i = 0; $i < count($clean); $i++) {
  if ( $i % 2 === 0) $obj[ $clean[$i] ] = $clean[$i+1];
}
// and convert it back to JSON notation
$jsonObj = json_encode($obj);
echo $jsonObj;
?>

INPUT (invalid json):

'{"id_content": "1"name": "Zappos Case Page 1"id_content_type": "1}'

OUTPUT (valid json):

'{"id_content":"1","name":"Zappos Case Page 1","id_content_type":"1"}'


This code will only work, if the pattern is always the same. Otherwise, you will have to addapt the code to the different scenarios.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. this works fine. yeah in my scenarios patterns are same.
i was looking for regular expression. thanks for updating your answer.
1

you can validate the json in JS itself by something like.

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

if its valid then send to server side and save into DB.

For existing data, you can not do anything. You might need to do correction manually using any online tool (http://json.parser.online.fr/) before saving to DB.

Comments

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.