Read JSON as a variable from a file - python

Trying to read a multi-line variable (JSON) from a file in python, but getting an error.
#config.py
A = {
"query" : {
"match_all" : { }
}
}
#client.py
from config import *
print A
I get {'query':{'match_all':{}}} <--- double quotes are replaced with single quotes. Is there a way to preserve the original?
Thanks,

The single quotes are there as a result of Python's representation of strings. If you really want the double quotes, you can do a trivial str.replace:
>>> print str(A).replace("'",'"')
{"query": {"match_all": {}}}

Related

UTF-8 characters in python string even after decoding from UTF-8?

I'm working on converting portions of XHTML to JSON objects. I finally got everything in JSON form, but some UTF-8 character codes are being printed.
Example:
{
"p": {
"#class": "para-p",
"#text": "I\u2019m not on Earth."
}
}
This should be:
{
"p": {
"#class": "para-p",
"#text": "I'm not on Earth."
}
}
This is just one example of UTF-8 codes coming through. How can I got through the string and replace every instance of a UTF-8 code with the character it represents?
\u2019 is not a UTF-8 character, but a Unicode escape code. It's valid JSON and when read back via json.load will become ’ (RIGHT SINGLE QUOTATION MARK).
If you want to write the actual character, use ensure_ascii=False to prevent escape codes from being written for non-ASCII characters:
with open('output.json','w',encoding='utf8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
You didn'T paste your code, so I don't kwon how you converted XHTML to JSON. I assume that you ended with hex value characters in Python objects. This \u2019 is a single character with a 16-bit hex value. The JSON module can handle this by default. For example, the json.loads method can fix that:
x = '''{
"p": {
"#class": "para-p",
"#text": "I\\u2019m not on Earth."
}
}'''
print(x)
x_json=json.loads(x)
print(x_json)
Output shows:
{
"p": {
"#class": "para-p",
"#text": "I\u2019m not on Earth."
}
}
{'p': {'#class': 'para-p', '#text': 'I’m not on Earth.'}}

Using Bad Json in Python

I am having a json in a file which i want to access in my Python Code. The Json file looks like :
{
"fc1" : {
region : "Delhi",
marketplace : "IN"
},
"fc2" : {
region : "Rajasthan",
marketplace : "IN"
}
}
The above json i want to use in my Python code. I want to access according to its keys("fc1", "fc2")
Since this is not like actual json, i am facing difficulty in accessing the values in json.
Is there any way in python language to access these type of json.
Thanks.
I agree with the comment that, if you generated that file, then you should put quotes around region and marketplace when generating it (or have the person who generated it do the same). However, if this absolutely isn't an option for whatever reason, the following approach might work:
import json
data_string = """
{
"fc1":{
region:"Delhi",
marketplace: "IN"
},
"fc2" : {
region:"Rajasthan",
marketplace: "IN"
}
}
"""
data = json.loads(data_string.replace('region', '"region"').replace('marketplace', '"marketplace"'))
data
>>>{'fc1': {'region': 'Delhi', 'marketplace': 'IN'},
'fc2': {'region': 'Rajasthan', 'marketplace': 'IN'}}
Note that you would have to do the same for any unquoted key.
There is module dirtyjson which reads this incorrect JSON.
import dirtyjson
data_string = """
{
"fc1":{
region:"Delhi",
marketplace: "IN"
},
"fc2" : {
region:"Rajasthan",
marketplace: "IN"
}
}
"""
data = dirtyjson.loads(data_string)
print(data)
print(data['fc1'])
print(data['fc2'])

How can I give a JSON object as parameter into a python file? [duplicate]

This question already has answers here:
How to pass dictionary as command line argument to Python script?
(9 answers)
Closed 6 years ago.
This is the json object:
{
"aaa": "111",
"bbb": "222",
"ccc": [{
"ddd ": "333",
"eee": "444"
}]
}
Currently this is working when I run the program in windows cmd:
MyProgram.py --myJSON "{ \"aaa\": \"111\", \"bbb\": \"222\", \"ccc\": [{ \"ddd\": \"333\", \"eee\": \"444\" }] }"
Is it possible to give in a JSON object as a string without '\' character?
You need the \ character to escape your string since you're using double quotes. Try this:
MyProgram.py --myJSON '{ "key": "value", ... }'
Of course, now you will need to use backslashes to escape single quotes. A better way to pass JSON into your program would be to store it in a file and then load it:
with open('my_json.json', 'r') as f:
json = f.read()
print json

Handling JSON string in python

i have an string for example
var = "{"name":"angelo","apellido":"enriquez"}"
but when doing the following function I get an error
data = json.loads(var)
Error : No JSON object could be decoded
Any help?
Replace your var with :
var = '{"name":"angelo","apellido":"enriquez"}'
i.e put the content inside {} within single quotes (') instead of double .
Hope that helps .
First of all you are not writing good json in javascript, replace inner " double quotes with single ' quotes.
var MyJSVar = {'hello':'bra'}
If string
var MyJSVar = "{'hello':'bra'}"

How to handle JSON with Python?

I'm very new to Python. I have a JSON response like this :
{
"Code" : "Success",
"LastUpdated" : "2012-10-19T08:52:10Z",
}
I need to get the value of Code, which is Success. How can I do that in Python?
Search for json in the documentation . You'll find the json module explained, with examples.
import json
# ... you read here from the file
data = '''{
"Code" : "Success",
"LastUpdated" : "2012-10-19T08:52:10Z"
}'''
result = json.loads(data)
print result['Code']
Be careful with the format!! I removed the comma after "LastUpdated" : "2012-10-19T08:52:10Z", because this is not a valid json.

Categories

Resources