PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] How to format the invalid JSON to a proper JSON format in PHP?

 December 29, 2021     formatting, json, php     No comments   

Issue

The below json string creating an issue while doing json_decode(). While removing the spaces, slashes, \n, it is working. Can someone suggest?

  {\n   \"long_format\":{\n      \"date\":\"DD/MM/YYYY\",\n      \"time\":\"H:mm:ss\",\n      \"date_time\":\"DD/MM/YYYY H:mm:ss\"\n   },\n   \"short_format\":{\n      \"date\":\"DD/MM/YY\",\n      \"time\":\"hh:mm:ss A\",\n      \"date_time\":\"DD/MM/YY hh:mm:ss A\"\n   }\n}

Solution

You can use preg_replace()

$string = preg_replace(array('/\\\\n\s+/m','/\\\\n/m','/\\\\"/m'), array('','','"'), $string);
print_r(json_decode($string,true));

Output: https://3v4l.org/GQhTO

Note: Its better to correct the source code which created this json data, in case you have control over that.



Answered By - Anant Kumar Singh
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing