Python json decoder jsondecodeerror expecting property name enclosed in double quotes

Python: нужно парсить JSON с лишней запятой

Конечно, если убрать запятую после последнего значения в словаре, то ошибки не будет. Но как обрабатывать JSON именно с запятой в конце словаря или списка? Это ведь мелочь, к тому же, JavaScript такое позволяет.

Например, такая задача может возникнуть в админ-консоли для быстрого ручного редактирования настроек, когда удаляешь последнюю запись – хотелось бы не напрягать юзера поиском иголки в стоге сена и правильным проставлением какой-то запятой.

Ответы (2 шт):

Дело в том, что официальный стандарт JSON предполагает некорректным наличие лишней запятой в конце списка или словаря, поэтому официальные парсеры будут ругаться на такую мелочь. Возможные решения:

1) «Починить» формат убрав лишний символ с помощью RegEx

>>> import re >>> s = '< "key1": "value1", "key2": "value2", >' >>> re.sub(r"\"\s*,\s*\>", "\" >", s) '< "key1": "value1", "key2": "value2" >' 
>>> import json >>> s2 = re.sub(r"\"\s*,\s*\>", "\" >", s) >>> json.loads(s2)

Но у этого метода есть важный недостаток, в определённых случаях он может испортить строку. Пример такой строки: < "foo": ",>» >

Читайте также:  Настроить css в pycharm

2) Использовать другой парсер

Есть такие альтернативы стандартному модулю json :

  • json5 – реализация стандарта JSON5. Позволяет использовать одно- и многострочные комментарии, многострочные строки, строки не только с » , но и с ‘ , а также запятые в конце списков/словарей.
  • jsoncomment – функционал в целом такой же, но модуль кажется не поддерживаемым и упомянут чисто в академических целях.

У этого способа тоже есть важный недостаток: к сожалению, сторонние библиотеки работают в десятки и сотни раз медленнее стандартного модуля, они сами это признают. Поэтому к выбору способа решения проблемы придётся подходить продуманно.

>>> s = '< "key1": "value1", "key2": "value2", >' >>> res=str(eval(s)).replace('\'', '"') >>> res '' >>> json.loads(res) >>> 

Источник

Почему не работает json.loads?

File «/home/olga/.pyenv/versions/3.9.0/lib/python3.9/json/decoder.py», line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

import json old = str() new = json.loads(old)

NeiroNx

import json old = json.dumps() new = json.loads(old)

такой вариант к сожалению мне не подходит, так как значение <"1": "red", "2": "black", "3": "green">я получаю из файла и это значение строковое

NeiroNx

Xe1ga, так у вас загруженная строка выглядит так: » ? Если да, то нет проблем к ней применить json.loads().

hottabxp

import json with open('data.txt') as file: data = file.read() json_data = json.loads(data) print(type(json_data)) print(json_data)
import json old = json.dumps(, indent = 4) new = json.loads(old) print(new['1'])

моя цель не словарь конвертировать в json, а на входе я имею строку, которая выглядит как словарь, поэтому к строке я не могу применить dumps

Источник

How to resolve JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) in Python

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

When programming, you may encounter JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). What is the cause of this error, and is there any way to deal with it? Details are revealed in the article below.

Читайте также:  How to find java home

What causes the JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)?

The error occurs because you use json.loads function to parse an invalid Json string.

import json invalidJsonStr = "" # Use the json.loads() function to parse a Json string into a Python dictionary dictObj = json.loads(invalidJsonStr) print('Json string converted to dictionary:', dictObj)
Traceback (most recent call last): File "./prog.py", line 6, in json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

How to solve the JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)?

Declare a valid Json string

As the cause of the error in the above example, you have declared an invalid Json string. The quotation marks you used to set your string are incorrect, so they are not accepted in the Json format.

  • All you need to do is declaring a valid Json string by placing single quotes to create the string, key-value pairs inside the string use double quotes.
import json validJsonStr = '' # Use the json.loads() function to parse a Json string into a Python dictionary dictObj = json.loads(validJsonStr) print('Json string converted to dictionary:', dictObj)
Json string converted to dictionary:

Use the json.dumps() function

If you are unsure about generating a valid Json string, you can use json.dumps function to do it.

  • I have a dictionary I want to convert to a Python string to use the Json.loads function, but I need clarification on declaring a valid Json string, so use the json.dumps function to convert the dictionary to a Json string.
  • The json.loads() function can then be used.
import json dictObj = # The json.dumps function serializes a Python object into a Json string convertToJsonStr = json.dumps(dictObj) # Use the json.loads() function to parse a Json string into a Python dictionary convertToDict = json.loads(convertToJsonStr) print(convertToDict)

Use ast.literal_evalph method

ast.literal eval, this is one of the aids for exploring an abstract syntax tree. This function evaluates an expression node, a string containing a Python character, or the container display.

Читайте также:  Stringify function in javascript

This method, ast.literal eval, securely evaluates strings containing Python values from untrusted sources without the need to interpret the contents.

import ast invalidJsonStr = "" # The ast.literal_eval can securely evaluate strings containing Python values from untrusted sources dictObj = ast.literal_eval(invalidJsonStr) print(dictObj)

Summary

Article on solving the JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) in Python is required. If there are other ways or ideas about the article, please leave a comment. Thanks for reading!

Maybe you are interested:

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

Оцените статью