从JSON字符串的键/值中删除引号(单/双)

时间:2022-06-01 16:46:55

Sample Input String:

示例输入字符串:

{"14" Alloy Wheels (Set of 4)":"N/A","Engine":"CrDi","15" Alloy Wheels":"optional","Other":"16" Wheels"};

{“14”合金轮(4件套)“:”N / A“,”发动机“:”CrDi“,”15“合金轮”:“可选”,“其他”:“16”轮“};

There are 4 possible cases:

有4种可能的情况:

{"key"here":

,"Key"here":

:"Value"here",

:"Value"here"}

I need to get rid of the inverted commas in between keys and values, which is causing

我需要摆脱键和值之间的引号,这是引起的

invalid json

when using json_decode in PHP.

在PHP中使用json_decode时。

One possible solution is using RegEx, but I am not able to formulate the above possible cases.

一种可能的解决方案是使用RegEx,但我无法制定上述可能的情况。

1 个解决方案

#1


I did some testing with your string and I came up with the following solution.

我用你的字符串做了一些测试,我提出了以下解决方案。

  1. Set json formatting apart from the rest
  2. 将json格式设置为与其余格式分开

  3. Correct the keys and values
  4. 更正键和值

  5. Restore json formatting

    恢复json格式

    function repairJson( $str) {
        $search = array( '":"', '","', '":{"', '"},"', '{"', '"}' );
        $replace = array("':'", "','", "':{'", "'},'", "{'", "'}" );
        // Distinct json default formatting
        $str = str_replace( $search, $replace, $str );
        // Find and replace all " that are not yet escaped
        $str = preg_replace( '/([^\\\])"/', '${1}\"', $str );
        // Restore json default formatting
        $str = str_replace( $replace, $search, $str );
        return $str;
    }
    

#1


I did some testing with your string and I came up with the following solution.

我用你的字符串做了一些测试,我提出了以下解决方案。

  1. Set json formatting apart from the rest
  2. 将json格式设置为与其余格式分开

  3. Correct the keys and values
  4. 更正键和值

  5. Restore json formatting

    恢复json格式

    function repairJson( $str) {
        $search = array( '":"', '","', '":{"', '"},"', '{"', '"}' );
        $replace = array("':'", "','", "':{'", "'},'", "{'", "'}" );
        // Distinct json default formatting
        $str = str_replace( $search, $replace, $str );
        // Find and replace all " that are not yet escaped
        $str = preg_replace( '/([^\\\])"/', '${1}\"', $str );
        // Restore json default formatting
        $str = str_replace( $replace, $search, $str );
        return $str;
    }